다음을 통해 공유


방법: LINQ 쿼리 결과에 바인딩

이 예제에서는 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}"/>

첫 번째 목록 상자에서 항목을 선택하면 다음 이벤트 처리기가 호출됩니다. 이 예제에서 Tasks는 Task 개체의 컬렉션입니다. Task 클래스에는 Priority라는 속성이 있습니다. 이 이벤트 처리기는 선택된 우선 순위 값을 가지는 Task 개체의 컬렉션을 반환하는 LINQ 쿼리를 실행한 다음 이를 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;
}

두 번째 목록 상자는 해당 ItemsSource 값이 {Binding}으로 설정되기 때문에 이 컬렉션에 바인딩됩니다. 그 결과, 반환된 컬렉션을 표시합니다(myTaskTemplate DataTemplate에 기반함).

참고 항목

작업

방법: XAML의 바인딩에 사용할 수 있는 데이터 만들기

방법: 선택에 따라 수집 및 표시 정보에 바인딩

개념

WPF 버전 4의 새로운 기능

데이터 바인딩 개요

기타 리소스

데이터 바인딩 방법 항목