此示例演示如何运行 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集合)。