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

WPF: Data Source Providers (XML)

Bài viết này trình bày cách thực hiện binding XML data trong WPF.

A21319952F68E79E_432_0[1]

Trước hết chúng ta có một XML file: Hyperlogy.xml

<?xml version="1.0" encoding="utf-8" ?>
<Company xmlns="http://www.hyperlogy.com">
  <Person FirstName="Duc" LastName="Le" />
  <Person FirstName="Quang" LastName="Nguyen" />
  <Person FirstName="Nhat" LastName="Mai" />
</Company>


Chúng ta thực hiện Binding XML file thông quan XAML code như sau:



- Sử dụng XmlDataProvider để khai báo XML Binding



- Source: chỉ ra xml source file



- XPath: chỉ ra collection element cần binding






<Window.Resources>
        <XmlDataProvider
            x:Key="Hyperlogy"
            Source="Hyperlogy.xml"
            XPath="/hy:Company/hy:Person">
                <XmlDataProvider.XmlNamespaceManager>
                <XmlNamespaceMappingCollection>
                    <XmlNamespaceMapping Uri="http://www.hyperlogy.com" Prefix="hy" />
                </XmlNamespaceMappingCollection>
                </XmlDataProvider.XmlNamespaceManager>
            </XmlDataProvider>
    </Window.Resources>


 



Sử dụng {Binding XPath=@FirstName} để binding tới các node của XML



Fullcode






<Window x:Class="XMLBinding.Window1"
   ...
    <Window.Resources>
        <XmlDataProvider
            x:Key="Hyperlogy"
            Source="Hyperlogy.xml"
            XPath="/hy:Company/hy:Person">
                <XmlDataProvider.XmlNamespaceManager>
                <XmlNamespaceMappingCollection>
                    <XmlNamespaceMapping Uri="http://www.hyperlogy.com" Prefix="hy" />
                </XmlNamespaceMappingCollection>
                </XmlDataProvider.XmlNamespaceManager>
            </XmlDataProvider>
    </Window.Resources>
    <Grid Margin="10" Name="grid" DataContext="{StaticResource Hyperlogy}">
       ...
        <ListBox Grid.Column="1" Grid.Row="0" Name="lbPeople" 
                 ItemsSource="{Binding}" 
                 IsSynchronizedWithCurrentItem="True">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock>
                        <TextBlock Text="{Binding XPath=@FirstName}"/>   
                        <TextBlock Text="{Binding XPath=@LastName}"/>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBox Grid.Column="1" Grid.Row="2" Name="txtFirstName" Text="{Binding XPath=@FirstName}" />
        <TextBox Grid.Column="1" Grid.Row="4" Name="txtLastName" Text="{Binding XPath=@LastName}"/>
        ...
    </Grid>
</Window>

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

Đăng nhận xét