简体   繁体   中英

Wpf DataGrid : changing the XML field binding at runtime

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM