Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Data-Driven GUIs with Data Binding

Trn Thanh Li L Th Thanh Tho

Mc Lc
1. Binding

2. ListView

3. Data Templates

4. Data Views

1. Binding
Data Binding l k thut dng to gn kt gia phn giao din (UI) v d liu. Tc dng : UI c th t ng cp nht li hin th cc thay i trong d liu. Ngoi ra, Data Binding trong WPF cn h tr cc chiu khc nhau, ngha l cc thay i c th cp nht t UI vo d liu.

Gii thiu
Mt Binding bao gm 4 thnh phn chnh l: 1. binding target 2. target property 3. binding source 4. mt path (ng dn) n gi tr cn thit trong binding source, thng thng path ny l mt source property.

V d gn property Name ca mt i tng Person cho property Text ca mt TextBox


Binding target: TextBox Target property: property Text ca TextBox Binding source: i tng Person Path: ng dn n property Name ca i tng Person.

<StackPanel> <TextBox x:Name="txtInput" /> <Label Content="{Binding Text, ElementName=txtInput, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel>

V d trong cun C# 2010 for Programmers (trang 870)

To d liu mu Cho ListView


class Book { public string Title { get; set; } public int ISBN { get; set; } public string ThumbImage { get; set; } public string LargeImage { get; set; } }

books.Add(new Book { Title = "AJAX, Rich Internet Applications, and Web Development for Programmers", ISBN = 0131587382, ThumbImage = "images/1.jpg", LargeImage = "images/1a.jpg" });

<ListView Grid.Column="0" Name="booksListView" > <ListView.View> <GridView> <GridViewColumn Header="Title" Width="100" DisplayMemberBinding="{Binding Path=Title}" /> <GridViewColumn Header="ISBN" Width="80" DisplayMemberBinding="{Binding Path=ISBN}" /> </GridView> </ListView.View> </ListView>

<Image Source="{Binding ElementName=booksListView,Path=SelectedItem.LargeImage}" />

DataTemplate
Miu t cu trc ca d liu c khi bo trong : <Window.Resources> <DataTemplate x:Key=khoa"> </DataTemplate> </Window.Resources>

Demo DataTemplate

Data Views
Data Views (l mt lp ca CollectionView) Mt collection cng c th c coi l mt i tng, tuy nhin vic binding loi d liu ny yu cu nhng chc nng nh sp xp, lc, gom nhm =>Vic s dng cc chc nng ny khng nh hng g n d liu ngun

WPF cng cung cp mt lp generic l ObservableCollection<T> c hin thc sn INotifyCollectionChanged bn s dng m khng cn to thm mt kiu collection mi. nhn d liu t Data Views dng Phng thc static CollectionViewSource.GetDefaultView() vi kiu tr v l System.ComponentModel.ICollectionView.

Filtering
Collection View cung cp mt property Filter c kiu Predicate<Object>. Kiu ny l mt delegate chp nhn mt tham s kiu object v tr v mt gi tr boolean da trn cc iu kin bn thc hin trn tham s .

Ti liu tham kho


http://yinyangit.wordpress.com/2011/09/09/wpf-data-binding-coban/ http://yinyangit.wordpress.com/2011/09/13/wpf-%E2%80%93-datatemplate-data-trigger-va-template-selector/

You might also like