Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF two-way binding XML

Tags:

c#

xml

binding

I'm struggling to get to grips with WPF, more specifically performing two way binding of an xml file. Should I be using XMLDataProvider or is their another(better) option? The data is displaying fine but when I change an entry the changes aren't reflected in the xml file.

The XML:

    <?xml version="1.0" encoding="utf-8" ?>
<Licence>
 <Market>
  <Name>DAX</Name>
  <Begin>01/01/2010</Begin>
  <End>01/04/2010</End>
 </Market>
 <Market>
  <Name>DJI</Name>
  <Begin>01/07/2010</Begin>
  <End>01/10/2010</End>
 </Market>
</Licence>

The XAML:

<Window x:Class="WpfApplication5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate x:Key="LicenceTemplate"> 
        <Label Content="{Binding XPath=Name}"/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Grid.DataContext>
        <XmlDataProvider x:Name="XMLData" Source="XMLFile1.xml" XPath="Licence/Market"/>

    </Grid.DataContext>
    <StackPanel>
        <DataGrid x:Name="DataGridLic"  ItemsSource="{Binding}" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="300" CellEditEnding="DataGridLic_CellEditEnding">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="nameColumn" Binding="{Binding XPath=Name, Mode=TwoWay}" Header="Name" Width="100" Foreground="#FFC28383" />
                <DataGridTextColumn x:Name="BegColumn" Binding="{Binding XPath=Begin, Mode=TwoWay}" Header="Begin" Width="100" Foreground="#FFC14040" />
                <DataGridTextColumn x:Name="EndColumn" Binding="{Binding XPath=End, Mode=TwoWay}" Header="End" Width="100" Foreground="#FFC14040" />
            </DataGrid.Columns>
        </DataGrid>


    </StackPanel>
</Grid>

The CodeBehind:

 public MainWindow()
    {
        InitializeComponent();
    }

    private void DataGridLic_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
       XMLData.Document.Save("XMLFile1.xml");
    }

UPDATE: Some useful resources for xml databinding:

http://msdn.microsoft.com/en-us/library/bb669141.aspx

http://msdn.microsoft.com/en-us/library/cc165615.aspx

like image 741
Chris Avatar asked Jul 20 '10 20:07

Chris


1 Answers

No problem using the XMLDataProvider. You just need to make sure you are reading and writing to the same XML file.

Just update your code as follows;

public MainWindow()
{
    InitializeComponent();
    var xmlFilePath = @"c:\whatever\XMLFile1.xml";
    XMLData.Source = new Uri(xmlFilePath);
}

private void DataGridLic_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
   var xmlSource = XMLData.Source.LocalPath;
   XMLData.Document.Save(xmlSource);
}
like image 76
obaylis Avatar answered Sep 22 '22 22:09

obaylis