在绑定到XML的DataGrid中添加一行

时间:2016-08-20 15:27:28

标签: c# xml wpf datagrid

我有一个绑定到XML文件的DataGrid。用户可以编辑行,但我似乎无法让它们添加行。

这是XML文件:

<?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>

这是DataGrid的XAML

<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>

以下是代码:

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");
}

0 个答案:

没有答案