Thứ Sáu, 24 tháng 7, 2009

WPF: Binding to LINQ data

Bài viết này trình bày cách binding to LINQ data trong WPF.

A21319952F68E79E_435_0[1]

Chúng ta có một class sử dụng LINQ như sau:

namespace LINQBinding
{
    public class Person
    {
        public string FullName { get; set; }
        public string Department { get; set; }
        public Person(string fullName, string department)
        {
            FullName = fullName;
            Department = department;
        }
    }
 
    public class People : List<Person> { }
 
    public class Hyperlogy
    {
        People people = new People         
        { 
        new Person("Duc Le", "Java"),
        new Person("Quang Nguyen", ".Net"),
        new Person("Huy Tran", "Java"),
        new Person("Nhat Mai", ".Net"),
        new Person("Nam Do", "Java"),
        };
 
        public IEnumerable<string> MicrosoftTeam
        {
            get
            {
                return from person in people
                       where person.Department == ".Net"
                       select person.FullName;
            }
        }
    }
}



Chúng ta có thể binding LINQ data trong MicrosoftTeam property của class trong XAML như sau:



Trước hết chúng ta khai báo window resource:






<Window.Resources>    
        <local:Hyperlogy x:Key="HyperlogyCompany"></local:Hyperlogy>
</Window.Resources>


Sau đó binding trong listbox sử dụng MicrosoftTeam property






<Grid DataContext="{StaticResource HyperlogyCompany}">
  <ListBox ItemsSource="{Binding Path=MicrosoftTeam}"></ListBox>
</Grid>



Fullcode






<Window x:Class="LINQBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="LINQ Data Binding" Height="200" Width="300" 
        xmlns:local="clr-namespace:LINQBinding">
    <Window.Resources>    
        <local:Hyperlogy x:Key="HyperlogyCompany"></local:Hyperlogy>
    </Window.Resources>
    <Grid DataContext="{StaticResource HyperlogyCompany}">
        <ListBox ItemsSource="{Binding Path=MicrosoftTeam}"></ListBox>
    </Grid>
</Window>

Không có nhận xét nào:

Đăng nhận xét