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


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:

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

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.


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

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


    • Very good articles so far. Thank you very much, Sean. 🙂

      What I didn’t understand here (still pretty new to WPF):

      Why is there an m:Movie in the beginning? Because it’s a movie? Or we can just select the latter?

      Like could it also have been:

      What would happen then?

      • Sean says:

        Your example got stripped out of the comment. But to answer the question:
        – This is just an example of creating an instance of a non-UI element in XAML. This isn’t all that common, but can be done. You might do this so that you can bind to a test class or something similar.
        – The “m:” part is a shortcut for the namespace defined at the top of the file.

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: