Donate

XmlDataProvider With TwoWay Binding In WPF

Hello,
Here's a simple example of two-way binding in WPF using XMLDataProvider. This post is taken from John Papa's example in MSDN magazine years ago but with minor errors. The XMLDataProvider markup has color values and is declared inside Window.Resources node.
<Window.Resources>
 <XmlDataProvider x:Key="MoreColors">
  <x:XData>
   <colors xmlns=''>
    <color name="pink"/>
    <color name="white"/>
    <color name="black"/>
    <color name="cyan"/>
    <color name="gray"/>
    <color name="magenta"/>
   </colors>
  </x:XData>
 </XmlDataProvider>
</Window.Resources>
The Textbox control's Text Text property binding has been set to TwoWay so when you enter a color name it will be added as a ListBox Item.
<Grid>
 <StackPanel>
  <TextBlock Width="248" Height="24" Text="Colors:" 
   TextWrapping="Wrap"/>
  <ListBox x:Name="lbColor" Width="248" Height="120" 
     IsSynchronizedWithCurrentItem="True"
     DataContext="{Binding Source={StaticResource MoreColors}}"
     ItemsSource="{Binding Mode=Default, XPath=/colors/node()}">
   <ListBox.ItemTemplate>
    <DataTemplate>
     <StackPanel Orientation="Horizontal">
      <TextBlock Text="{Binding XPath=@name}" />
     </StackPanel>
    </DataTemplate>
   </ListBox.ItemTemplate>
  </ListBox>
  <TextBlock Width="248" Height="24" Text="You selected color:" />
  <TextBlock Width="248" Height="24" 
       DataContext="{Binding ElementName=lbColor, Path=SelectedItem}" 
       Text="{Binding XPath=@name}"
       Background="{Binding XPath=@name}"/>
  <TextBox Width="248" Height="24" 
     DataContext="{Binding ElementName=lbColor, Path=SelectedItem}" 
     Text="{Binding XPath=@name, Mode=TwoWay}"
     x:Name="TxtSelectedColorBox"
     Background="{Binding XPath=@name, Mode=OneWay}"/>
 </StackPanel>
</Grid>

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations