有没有人能为我提供一个好的资源(或者给我一些提示),告诉我如何在 WPF 中对控件(ComboBox、ListBox 等)进行数据绑定?当我失去所有 WinForms 的好东西时,我有点莫名其妙,而且一开始就不是很聪明...
有没有人能为我提供一个好的资源(或者给我一些提示),告诉我如何在 WPF 中对控件(ComboBox、ListBox 等)进行数据绑定?当我失去所有 WinForms 的好东西时,我有点莫名其妙,而且一开始就不是很聪明...
在代码后端,将您的列表框的DataContext设置为您要绑定到的集合。
private void OnInit(object sender, EventArgs e)
{
//myDataSet is some IEnumerable
// myListBox is a ListBox control.
// Set the DataContext of the ListBox to myDataSet
myListBox.DataContext = myDataSet;
}
<ListBox Name="myListBox" Height="200"
ItemsSource="{Binding Path=BookTable}"
ItemTemplate ="{StaticResource BookItemTemplate}"/>
如果上面的内容还不够,这里有更多链接:
Windows Presentation Foundation - 数据绑定教程
- 大约30篇来自MSDN的“如何”文章。
“本节中的主题描述了如何使用数据绑定将元素绑定到各种数据源中的数据,这些数据以公共语言运行时(CLR)对象和XML的形式存在。”
一步一步接近WPF数据绑定
- 由WPF专家Josh Smith撰写
“本文解释了WPF数据绑定的绝对基础知识。它展示了四种不同的方法来执行相同的简单任务。每个迭代都更接近最紧凑的仅限XAML实现。本文适用于没有WPF数据绑定经验的人。”
public class EmailAddress
{
public string AddressAsString { get; set; }
}
public class Person
{
public IEnumerable<EmailAddress> EmailAddresses { get; }
public EmailAddress MainEmailAddress { get; set; }
}
<ComboBox ItemsSource="{Binding EmailAddresses}" SelectedItem="{Binding MainEmailAddress}">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem Content="{Binding AddressAsString}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>