6.3.7 使用集合对象作为列表控件的ItemsSource
<StackPanel x:Name="stackPanel" Background="LightBlue">
<TextBlock Text="Student ID:" FontWeight="Bold" Margin="5"/>
<TextBox x:Name="textBoxId" Margin="5"/>
<TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/>
<ListBox x:Name="listBoxStudents" Height="110" Margin="5">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Id}" Width="30"/>
<TextBlock Text="{Binding Path=Name}" Width="60"/>
<TextBlock Text="{Binding Path=Age}" Width="30"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
public partial class MainWindow : Window
{
List<Student> stuList = new List<Student>()
{
new Student(){Id = "0", Name = "Anders", Age = 27},
new Student(){Id = "1", Name = "Xuyang", Age = 34}
};
public MainWindow()
{
InitializeComponent();
this.listBoxStudents.ItemsSource = stuList;
this.textBoxId.SetBinding(TextBox.TextProperty, new Binding("SelectedItem.Id") { Source = listBoxStudents, Mode = BindingMode.OneWay });
}
}
6.3.8 使用ADO.NET对象作为Binding的源
<StackPanel x:Name="stackPanel" Background="LightBlue">
<TextBlock Text="Student ID:" FontWeight="Bold" Margin="5"/>
<TextBox x:Name="textBoxId" Margin="5"/>
<TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/>
<ListView x:Name="listViewStudents" Height="130" Margin="5">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding Path=Id}"/>
<GridViewColumn Header="Name" Width="80" DisplayMemberBinding="{Binding Path=Name}"/>
<GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding Path=Age}"/>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
public MainWindow()
{
InitializeComponent();
//Another bind source method
//this.listViewStudents.ItemsSource=Load().DefaultView;
this.listViewStudents.DataContext = Load();
this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
this.textBoxId.SetBinding(TextBox.TextProperty, new Binding("SelectedItem.Id") { Source = listViewStudents, Mode = BindingMode.OneWay });
}
private DataTable Load()
{
var connStr = "Data Source=(local);Initial Catalog=AndersDB;Integrated Security=True";
SqlCommand sqlComm = new SqlCommand("select * from Student", new SqlConnection(connStr));
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlComm);
DataSet ds = new DataSet();
sqlDA.Fill(ds);
return ds.Tables[0];
}