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?
Make sure that you set: CanUserAddRows="True"
and that the default constructor of a bound class is available.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With