WPF: Defining an instance in XAML

This entry is part 30 of 54 in the series Learn WPF

In WPF, we can actually create an instance of a Class such as the PopStar in the example below by defining it in the XML namespace.

<Window x:Class="CustType.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CustType"
        Title="MainWindow" Height="350" Width="525">
    <Label FontSize="20">
        <local:PopStar Name="Pitbull" 
             Album="Wild Wild Love" Price="12" 
               YearReleased="2013" />
    </Label>
</Window>

Notice that line 7 is actually the content of the Label control.

In line 7, we are actually creating an instance of a class called PopStar.  We have local:PopStar and so when the XAML is compiled, it will look for a class defined in clr-namespace:Custtype.

This actually corresponds to CustType namespace in MainWindow.xaml.cs.

using System.Windows;

namespace CustType
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    class PopStar
    {
        public string Name { get; set; }
        public string Album { get; set; }
        public decimal Price { get; set; }
        public int YearReleased { get; set; }


        public override string ToString()
        {
            return string.Format("{0} by {1}\nReleased {2}", Album, Name, YearReleased);
        }

    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

The output from running the above code is as below.  The output is actually formatted by line 32 by overriding the ToString method.

instanceXAML

To illustrate the example better, I can also add another instance in the XAML.

<Window x:Class="CustType.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CustType"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
     <Label FontSize="20">
        <local:PopStar Name="Pitbull" 
             Album="Wild Wild Love" Price="12" 
               YearReleased="2013" />
     </Label>
     <Label FontSize="20">
        <local:PopStar Name="Madonna" 
         Album="Immaculate Collection" Price="10" 
           YearReleased="1991" />
     </Label>
    </StackPanel>
</Window>

The output from running the above code will be:

instance2

 

 

Series Navigation<< WPF: Adding items to listbox
WPF: Changes in binding elements >>