basquang™ on clouds

July 24, 2009

WPF: Binding to LINQ data

Filed under: WPF — basquang @ 10:15 AM

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

image

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>
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: