Nasıl Yapılır: LINQ Sorgusunun Sonuçlarına Bağlama
This example demonstrates how to run a LINQ query and then bind to the results.
Örnek
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).
Ayrıca bkz.
Görevler
Nasıl Yapılır: XAML'de Bağlama için Veriyi Kullanılabilir Yapma
Nasıl Yapılır: Koleksiyona Bağlama ve Seçim Temelinde Bilgi Görüntüleme