Thứ Hai, 14 tháng 12, 2009

WPF: DataBinding là gì?

1. DataBinding là gì?

DataBinding là sự gắn kết hay ràng buộc về dữ liệu. Để cho dễ hiểu chúng ta có thể ví DataBinding giống như Map ổ đĩa vậy.


2. Kiểu DataBinding (DataBinding mode)

Có 2 kiểu DataBinding:

- Một chiều (OneWay) là dữ liệu (Data source) thay đổi thì giao diện người dùng (User Interface) thay đổi.

- Hai chiều (TwoWay) là nếu dữ liệu (Data source) thay đổi thì giao diện người dùng thay đổi và ngược lại.


3. Loại DataBinding

- DataBinding là 1 Object.

- DataBinding là 1 DataSource


Để hiểu sâu hơn về DataBinding thì tham khảo http://msdn.microsoft.com/en-us/library/ms750612.aspx


Sample (Window1.Xaml) code:









<Window x:Class="DataBinding.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="DataBinding
sample"
WindowStartupLocation="CenterScreen"
Height
="200" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="20" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
            <ListBox Grid.Row="0"
Grid.Column="0" Height="50"  Width="100" x:Name="listBox1"
SelectedIndex
="0" >
                <ListBoxItem>Red</ListBoxItem>
                <ListBoxItem>Yellow</ListBoxItem>
                <ListBoxItem>Green</ListBoxItem>
            </ListBox>
        <ListBox Grid.Column="1"
Grid.Row="0" Height="50"  Width="100"
                 x:Name="listBox2" SelectedIndex="{Binding ElementName=listBox1, Path=SelectedIndex, Mode=TwoWay}"
                 >
            <ListBoxItem>Red</ListBoxItem>
            <ListBoxItem>Yellow</ListBoxItem>
            <ListBoxItem>Green</ListBoxItem>
        </ListBox>
        <TextBlock Grid.Row="1"  Grid.ColumnSpan="2" Height="28" Name="label1" Width="100"
                   Text="{Binding ElementName=listBox1, Path=SelectedItem.Content}"
                   Background="{Binding ElementName=listBox1, Path=SelectedItem.Content}"/>
        <StackPanel Grid.Row="2"
Grid.ColumnSpan="2">
            <TextBlock>Binding mode:</TextBlock>
            <TextBlock Foreground="Blue"
TextWrapping="Wrap">OneWay: Nếu Listbox thay đổi thì Textblock thay đổi. Chỉ một chiều</TextBlock>
            <TextBlock Foreground="Gray"
TextWrapping="Wrap">TwoWay: Nếu SelectedIndex của Listbox bên trái thay đổi thì SelectedIndex
của Listbox bên phải thay đổi và ngược lại.</TextBlock>
        </StackPanel>
    </Grid>
</Window>
 

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

Đăng nhận xét