Search code examples
c#wpfxamlwpfdatagrid

WPF DataGrid: How to perform column binding using code behind?


This is the column in question:

<DataGridTextColumn
    Header=" Length "
    Width="Auto"
    Binding="{Binding Path=Length, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=0.00;;#}"
    ElementStyle="{StaticResource RightJustified}"
    x:Name="lengthColumn">
</DataGridTextColumn>

The problem is that I need to bind that column to some other property (called Length48) at run time.

TIA.


Solution

  • Try this:

    DataGridTextColumn dataGridTextColumn = new DataGridTextColumn();
    dataGridTextColumn.Header = " Length ";
    dataGridTextColumn.Binding = new Binding("Length48");
    
    YourDataGrid.Columns.Add(dataGridTextColumn);