Search code examples
c#.netwpfdata-bindingdatatemplate

WPF binding to single control (not a list)


In a nutshell, what I'm trying to do, is create a DataTemplate to indicate how a customer banner should look.

I've got this working in a very simple form, but only using a ListView control, to which I apply the ItemsSource to a list which contains one entry.

What I want to do is apply a Customer object directly to a control (not sure what type of control) and it picks up the DataTemplate for this type and lays out the data.

The xaml I'm using is...

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication5"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Customer}" >
            <Border Background="Blue" >
                <TextBlock Text="{Binding CustomerName}"  />
            </Border>
        </DataTemplate>
    </Window.Resources>
    <ListView x:Name="mylist" />
</Window>

With the following code-behind.

namespace WpfApplication5
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Customer mp=new Customer();
            mp.CustomerName="Mr. Banana";
            List<Customer> temp = new List<Customer>();
            temp.Add(mp);
            mylist.ItemsSource = temp;
        }
    }
    public class Customer
    {
        public string CustomerName { get; set; }
    }
}

Solution

  • Just use a ContentControl:

    <ContentControl x:Name="banner" />
    

    and in code:

    banner.Content = mp;