1、集合对象
WPF列表式控件派生自ItemsControl类,自然也就继承了ItemsSource这个属性。ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值(所有可被迭代遍历的集合都实现了这个接口,例如:List<T>)。每个ItemsControl的派生类都具有自己对应的条目容器。例如ListBox的条目容器就是ListBoxItem。ItemsSource里存放的是一条一条的数据,要想把数据显示出来需要为它们穿上外衣,条目容器就起到数据外衣的作用。怎样让每件数据外衣与它对应的数据条目关联起来呢?当然要依靠Binding。只要我们为一个ItemsSource对象设置了ItemsSource属性,并使用Binding在条目容器与数据元素之间建立关联。下面看一个例子:
<Window x:Class="BindingResearch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingResearch"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<TextBlock Text="Student ID:" Margin="5"/>
<TextBox x:Name="txtStuID" Margin="5"/>
<TextBlock Text="Student List:" Margin="5"/>
<ListBox x:Name="lstStudent" Margin="5"/>
</StackPanel>
</Window>
ListBox就是集合对象,下面看后台代码:
List<Student> listStudents = new List<Student>()
{
new Student(){ID=1,Name="Tim",Age=29},
new Student(){ID=2,Name="Tom",Age=30},
new Student(){ID=3,Name="Kyle",Age=31},
};
public MainWindow()
{
InitializeComponent();
lstStudent.ItemsSource = listStudents;
lstStudent.DisplayMemberPath = "Name";
Binding binding = new Binding("SelectedItem.ID") { Source = lstStudent };
txtStuID.SetBinding(TextBox.TextProperty, binding);
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
运行效果:
我们直接把List<Student>的实例赋值给ListBox的ItemSource,设置ListBox的显示字段为Name,ListBox的赋值就完成了。
当我们单机选中ListBox的一个条目时,上面的文本框就会显示选中条目的ID。
2、ADO.NET对象
ADO.NET对象就是从数据库中查询出来的数据集,一般情况下使用DataTable来存放。我们这里就不访问数据库了,直接新建一个DataTable对象。直接看代码吧:
<Window x:Class="BindingResearch.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingResearch"
mc:Ignorable="d"
Title="Window2" Height="450" Width="800">
<StackPanel>
<ListView x:Name="listViewStudents">
<ListView.View>
<GridView>