环境:VS2008 SP1+Northwind数据库
1.直接在代码中使用ItemsSource进行绑定
Data.NorthwindDataContext context = new Data.NorthwindDataContext();
var customer = from c in context.Customers
select c;
//this.DataContext = customer;
listBox1.ItemsSource = customer;
listBox1.DisplayMemberPath = "CompanyName";
XAML 代码:(默认即可)
<ListBox Name="listBox1"/>
2.如果页面中其余的控件如TextBox需要和ListBox使用同一数据源,使用上面的方法就不行了,必须使用DataContext属性。
Data.NorthwindDataContext context = new Data.NorthwindDataContext();
var customer = from c in context.Customers
select c;
this.DataContext = customer;
XAML代码:
<ListBox Name="listBox1" ItemsSource="{Binding Path={}}" DisplayMemberPath="CompanyName" />
<TextBox Grid.Row="1" Name="textBox1" Text="{Binding Path=Address}"/>
此时,TextBox中的值是固定的,和ListBox无关。如果想使TextBox中的值和ListBox进行联动就必须在ListBox中添加IsSynchronizedWithCurrentItem="True"
3.ListBox中显示类似表格
<ListBox Name="listBox1" ItemsSource="{Binding Path={}}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Width="150" x:Name="lblCompanyName" Content="{Binding Path=CompanyName}"/>
<Label Width="150" x:Name="lblContactName" Content="{Binding Path=ContactName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>