WPF学习笔记9. Binding (2)
2010-10-11 16:23:12 来源:本站整理4. 绑定到集合
在实际开发中,我们通常是将一个集合数据对象 (比如数据表) 绑定到一个 DataGrid 或者 ListBox 列表控件上,这时候我们就需要使用到集合绑定方式。WPF 特意为我们实现了一个 System.Collections.ObjectModel.ObservableCollection<T> 泛型集合,省却了我们写具备变更通知功能集合代码的时间。
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<StackPanel>
<ListBox x:Name="listbox1"></ListBox>
</StackPanel>
</Grid>
</Window>
Window1.xaml.cs
public class Personal
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
public class PersonalList : ObservableCollection<Personal>
{
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var list = new PersonalList
{
new Personal { Name = "Tom", Age = 10, Sex = "Male" },
new Personal { Name = "Mary", Age = 15, Sex = "Female" },
new Personal { Name = "Jack", Age = 12, Sex = "Male" },
};
var binding = new Binding{ Source = list };
this.listbox1.SetBinding(ListBox.ItemsSourceProperty, binding);
this.listbox1.DisplayMemberPath = "Name";
}
}
注意使用 DisplayMemberPath 属性指定 ListBoxItem 的内容,否则会调用 ToString() 来显示结果。
当然,我们也可以直接绑定逻辑资源中的列表数据。
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Learn.WPF"
Title="Window1">
<Window.Resources>
<my:PersonalList x:Key="personals" >
<my:Personal Name="Tom" Age="10" Sex="Male" />
<my:Personal Name="Mary" Age="15" Sex="Female" />
<my:Personal Name="Jack" Age="12" Sex="Male" />
</my:PersonalList>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listbox2"
ItemsSource="{Binding Source={StaticResource personals}}"
DisplayMemberPath="Name">
</ListBox>
</StackPanel>
</Grid>
</Window>
赞助商链接