简体   繁体   中英

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; }
    }
}

Just use a ContentControl :

<ContentControl x:Name="banner" />

and in code:

banner.Content = mp;

Create your own UserControl which will contain Customer property available for binding. Then you could bind to that property using RelativeSource binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM