WPF XmlDataProvider and XmlBinding in VB.NET

In this article, I will describe you how XmlBinding will be done using XmlDataProvider in WPF.
  • 2471

WPF also supports binding to Xml data in addition to object and relational data. For instance following example shows family data represented in Xml.
A random family rendered in Xml

<x:XData>
   <Company xmlns="http://company.com">
       <Employee Name="A" Age="11" />
       <Employee Name="B" Age="12" />
       <Employee Name="C" Age="38" />
   </Company>
</x:XData>

With this file available in the same folder as the executing application, we can bind to it using the XmlDataProvider, as shown below.

<Window x:Class="XmlBinding.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:WpfApplication22.XmlBinding"
  Title="XmlBinding" Height="325" Width="400">
    <Window.Resources>
        <XmlDataProvider x:Key="Company" XPath="/sb:Company/sb:Employee">
            <XmlDataProvider.XmlNamespaceManager>
                <XmlNamespaceMappingCollection>
                    <XmlNamespaceMapping Uri="http://company.com" Prefix="sb" />
                </XmlNamespaceMappingCollection>
            </XmlDataProvider.XmlNamespaceManager>
            <x:XData>
                <Company xmlns="http://company.com">
                    <Employee Name="A" Age="11" />
                    <Employee Name="B" Age="12" />
                    <Employee Name="C" Age="38" />
                </Company>
            </x:XData>
        </XmlDataProvider>
 
        <local:AgeToForegroundConverter x:Key="ageConverter" />
    </Window.Resources>
    <StackPanel DataContext="{StaticResource Company}">
        <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">
           <ListBox.GroupStyle>
                <x:Static Member="GroupStyle.Default" />
            </ListBox.GroupStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock>
            <TextBlock Text="{Binding XPath=@Name}" />
            (age: <TextBlock Text="{Binding XPath=@Age}" Foreground="{Binding XPath=@Age, Converter={StaticResource ageConverter}}" />)
          </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBlock>Name:</TextBlock>
        <TextBox Text="{Binding XPath=@Name}" />
        <TextBlock>Age:</TextBlock>
        <TextBox Text="{Binding XPath=@Age}" Foreground="{Binding XPath=@Age, Converter={StaticResource ageConverter}}" />
    </StackPanel>
</
Window>

OUTPUT

XmlBinding.gif

I hope this article will help you. 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.