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.

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:

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 myTaskTemplateDataTemplate).

Make Data Available for Binding in XAML
Bind to a Collection and Display Information Based on Selection
What's New in WPF Version 4.5
Data Binding Overview
How-to Topics

Show: