0

I have a DataGrid bound to an XML file. The user can edit the rows but I can't seem to get it to allow them to add rows.

Here is the XML File:

<?xml version="1.0" encoding="utf-8"?>
<Golf>
  <Golfers>
    <Golfer Name="John User" Handicap="87" Playing="True" />
    <Golfer Name="Betty Boop" Handicap="85" Playing="true" />
    <Golfer Name="Pro Master" Handicap="87" Palying="False" />
  </Golfers>
  <Courses>
    <Course Name="Course 1" Par="3" HasFront9="True" HasBack9="false" />
    <Course Name="Course 2" Par="3" HasFront9="False" HasBack9="True" />
    <Course Name="Course 3" Par="5" HasFront9="True" HasBack9="True" />
  </Courses>
</Golf>

Here is the XAML for the DataGrid

<DataGrid x:Name="GolfersDataGrid" HorizontalAlignment="Left" Margin="10,10,0,10" Width="227" CanUserAddRows="True"
          ItemsSource="{Binding Path=Elements[Golfer]}" MinColumnWidth="10" AutoGenerateColumns="False" BorderThickness="1" GridLinesVisibility="Horizontal" ColumnWidth="Auto">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Playing" Width="SizeToCells" Binding="{Binding Path=Attribute[Playing].Value}"/>
        <DataGridTextColumn Header="Golfer" Binding="{Binding Path=Attribute[Name].Value}"/>
        <DataGridTextColumn Header="Handicap" Binding="{Binding Path=Attribute[Handicap].Value}"/>
    </DataGrid.Columns>
</DataGrid>

Here is the code:

public XElement mGolfersList = XElement.Load("Resources\\Golf.xml");
private IEnumerable<XElement> mGolfers = null;

public MainWindow()
{
    InitializeComponent();

    mGolfers = from Golfer in mGolfersList.Elements("Golfers")
              select Golfer;
    GolfersDataGrid.DataContext = mGolfers;

}

private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    mGolfersList.Save("Resources\\Golf.xml");
}
Chris
  • 2,955
  • 1
  • 30
  • 43
HeyBob
  • 1
  • 1
  • You may want to look at this tree view solution : http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng Aug 20 '16 at 19:24
  • I think the reason is that the datacontext is only bound to the result of reading the file and not the file itself. You want to bind the two together, here's an example : http://www.c-sharpcorner.com/uploadfile/mamta_m/binding-xml-to-a-wpf-datagrid/ – JWP Aug 23 '16 at 03:47

0 Answers0