我想让我ComboBox
在 XAML 中绑定到我List
在代码后面的自定义对象集合。
目前ComboBox
每个条目的列表dpwpf.Contact
是 my {namespace}.{classname}
.
我需要在 XAML 中输入什么来告诉它列出,例如 LastName + FirstName?
我知道这有点像{Binding Path=... Value=...}
,但我无法理解。
XAML:
<Window x:Class="dpwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<StackPanel>
<TextBlock Text="Select the contact:"/>
<ComboBox Name="theContactList"/>
</StackPanel>
</StackPanel>
</Window>
代码背后:
namespace dpwpf
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
StoreDB db = new StoreDB();
List<Contact> contacts = db.GetContacts()
theContactList.ItemsSource = contacts.ToList();
}
}
}
回答:
<Window x:Class="dpwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:dpwpf">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Contact}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding FirstName}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<StackPanel Margin="10">
<TextBlock Text="Contact Name:" Foreground="#555"/>
<TextBox Name="theName"/>
</StackPanel>
<StackPanel>
<TextBlock Text="Select the contact:"/>
<ComboBox Name="theContactList"/>
</StackPanel>
</StackPanel>
</Window>