HOW TO:繫結至 LINQ 查詢結果

更新:2007 年 11 月

本範例示範如何執行 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}"/>

從第一個清單方塊選取項目會叫用 (Invoke) 下列事件處理常式。在這個範例中,Tasks 是 Task 物件的集合。Task 類別 (Class) 具有名稱為 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}。因此,它會顯示傳回的集合 (依據 myTaskTemplateDataTemplate)。如需完整範例,請參閱 LINQ 查詢範例

請參閱

工作

HOW TO:讓資料可於 XAML 中繫結

HOW TO:繫結至集合並根據選取項目顯示資訊

概念

Windows Presentation Foundation 3.5 版的新功能

資料繫結概觀

其他資源

資料繫結範例

資料繫結 HOW TO 主題