Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new row in WPF DataGrid when it is bound to an XmlDataProvider?

I have a project with an XmlDataProvider bound to a WPF DataGrid control. I have the bindings on the DataGrid set up as follows:

<dg:DataGrid ItemsSource="{Binding Source={StaticResource XmlData}, XPath=Root/People/Person}"
             AutoGenerateColumns="False">
    <dg:DataGrid.Columns>
        <dg:DataGridTextColumn Header="ID" Binding="{Binding XPath=ID}"/>
        <dg:DataGridTextColumn Header="Name" Binding="{Binding XPath=Name}"/>
    </dg:DataGrid.Columns>
</dg:DataGrid>

Users can edit entries using the DataGrid without any problems. What I cannot manage to accomplish is allowing the user to add a new row (i.e. a new Person) using the DataGrid. How can I allow this?

like image 746
bluepolystyreneman Avatar asked Jan 26 '09 15:01

bluepolystyreneman


2 Answers

Make sure that you set: CanUserAddRows="True" and that the default constructor of a bound class is available.

like image 154
Boris Lipschitz Avatar answered Oct 05 '22 10:10

Boris Lipschitz


To add a row to a WPF DataGrid that is bound to an XmlDataSource, you need to directly modify the backing data store. You can use the DataGrid to collect the new row information from the user and then in the RowEditEnding event, you can add the row's information to your backing store and prevent the DataGrid from actually trying to commit the edit using its internal logic. Since the DataGrid is bound to the XmlDataSource, it will display the changes you made to the backing store.

Here is the general idea:

private void MyDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
  if (e.EditAction == DataGridEditAction.Cancel)
  {
    e.Cancel = false;
    return;
  }

  if (e.EditAction == DataGridEditAction.Commit)
  {
    DataGridRow dgr = e.Row;
    XmlElement xe = myXmlDataProvider.Document.CreateElement("NewRowElement");
    foreach(DataGridCell cell in dgr.Cells)
    {
      xe.SetAttribute(cell.Name, cell.Value);
    }
    dataProvider.Document.DocumentElement.AppendChild(xe);
    e.Cancel = true;
  }
}
like image 27
Timothy Lee Russell Avatar answered Oct 05 '22 10:10

Timothy Lee Russell