如何:绑定到 LINQ 查询的结果
此示例介绍如何运行 LINQ 查询,然后绑定到结果。
示例
以下示例创建两个列表框。 第一个列表框包含三个列表项。
<ListBox SelectionChanged="ListBox_SelectionChanged"
SelectedIndex="0" Margin="10,0,10,0" >
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
<ListBox Width="400" Margin="10" Name="myListBox"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource myTaskTemplate}"/>
从第一个列表框中选择项会调用以下事件处理程序。 在此示例中,Tasks
是 Task
对象的集合。 Task
类有一个名为 Priority
的属性。 此事件处理程序运行 LINQ 查询,该查询返回具有所选优先级值的 Task
对象集,然后将其设置为 DataContext:
using System.Linq;
Tasks tasks = new Tasks();
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int pri = Int32.Parse(((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString());
this.DataContext = from task in tasks
where task.Priority == pri
select task;
}
第二个列表框绑定到该集合,因为其 ItemsSource 值设为 {Binding}
。 因此,它会显示返回的集合(基于 myTaskTemplate
DataTemplate)。