#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #99 – Creating Custom Objects in XAML

  1. Pingback: #157 – You Can Set Standard CLR Properties from XAML « 2,000 Things You Should Know About WPF

  2. Hannes says:

    Yey if red the first 100.
    Great work till now, so i have to read continue.

    Cheers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: