Expand Minimize

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:


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


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

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft