#99 – Creating Custom Objects in XAML

In XAML, you normally create elements that come from the standard WPF and XAML namespaces.  But you can also create objects that are instances of your own custom classes, or standard .NET classes in other namespaces.

You start by including a new namespace attribute, to indicate the namespace and assembly where your class can be found.  In the following example, we set up the m: prefix as pointing to the namespace MyStuff, which is in the assembly MyStuffLib.dll.

 xmlns:m="clr-namespace:MyStuff;assembly=MyStuffLib"

Now we can instantiate objects from the MyStuff namespace.  Assuming that MyStuff includes a Movie class, we could create an instance of a Movie in a window’s resource dictionary:

 <Window.Resources>
     <m:Movie x:Key="movie1" Title="Dances With Wolves" Director="Kevin Costner"/>
 </Window.Resources>

One reason for doing this would be so that we could then use data binding to bind one or more controls to the custom object.

Follow

Get every new post delivered to your Inbox.

Join 377 other followers