Wpf DataGrid : changing the XML field binding at runtime
-
03-07-2019 - |
Question
I am developing a WPF User Control for displaying portions of XML files. I'm trying to make the User Control flexible, so that I can assign the column headings and field data bindings from the outside of the control.
I've found that I can easily change the column headings, but while the following code seemed to have promise, SertMemberPath doesn't change the field binding
public void ChangeColumnDefinitions ( List<XmlGridColumnDefinition> columns )
{
int columnnum = 0;
foreach ( XmlGridColumnDefinition column in columns )
{
this.datagrid.Columns[columnnum].Header = column.Heading;
this.datagrid.Columns[columnnum].SortMemberPath = string.Format ( "Element[{0}].Value", column.FieldName );
++columnnum;
}
}
Solution
After looking around more I found this question and answer by @Generic_Error on SO. I modified his code slightly and here is what I came up with this which I can customize further.
public void ChangeColumnDefinitions ( IEnumerable<XmlGridColumnDefinition> columns )
{
this.datagrid.Columns.Clear ();
foreach ( var column in columns )
{
DataGridTextColumn coldef = new DataGridTextColumn
{
Header = column.Heading,
Binding = new Binding ( string.Format ( "Element[{0}].Value", column.FieldName ) )
};
this.datagrid.Columns.Add ( coldef );
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow