How to: Bind to the Results of a LINQ Query

This example demonstrates how to run a LINQ query and then bind to the results.

Example

The following example creates two list boxes. The first list box contains three list items.

<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}"/>

Selecting an item from the first list box invokes the following event handler. In this example, Tasks is a collection of Task objects. The Task class has a property named Priority. This event handler runs a LINQ query that returns the collection of Task objects that have the selected priority value, and then sets that as the DataContext:

Imports System.Linq


...


        Private tasks As New Tasks()


...


        Private Sub ListBox_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
            Dim pri As Integer = Int32.Parse((TryCast((TryCast(sender, ListBox)).SelectedItem, ListBoxItem)).Content.ToString())

            Me.DataContext = From task In tasks
                             Where task.Priority = pri
                             Select task
        End Sub
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;
}

The second list box binds to that collection because its ItemsSource value is set to {Binding}. As a result, it displays the returned collection (based on the myTaskTemplate DataTemplate).

See Also

Tasks

How to: Make Data Available for Binding in XAML

How to: Bind to a Collection and Display Information Based on Selection

Concepts

What's New in WPF Version 4

Data Binding Overview

Other Resources

Data Binding How-to Topics