Wpf – How to bind WPF Grid Column Width in code

bindinggridwpf

In WPF I have a Grid with a number of columns defined and the Width of each column is bound to the width of a DataGrid column, like so:

<Grid.ColumnDefinitions>
   <ColumnDefinition Width="{Binding ElementName=dataGrid, Path=RowHeaderWidth}" />
   <ColumnDefinition Width="{Binding ElementName=Column0, Path=ActualWidth}" />
   <ColumnDefinition Width="{Binding ElementName=Column1, Path=ActualWidth}" />
   Etc.

<Controls:DataGrid BorderBrush="White"  ItemsSource="{Binding DataTable}"  
                   Name="datagrid1" Grid.Row="2" RowHeaderWidth="0">

    <Controls:DataGrid.Columns>
    <Controls:DataGridTextColumn  Header="Included"  Width="50" x:Name="Column0" />
    <Controls:DataGridTextColumn  Header="First" Width="100" x:Name="Column1" />
     Etc.

When I run the program and manually resize the columns, I can see the Grid columns resizing (ShowGridLines = true) and elements tied to particular Grid columns move appropriately.

However, when I try to add the data grid and Grid columns in code I can’t get the binding to work (no binding errors). Here is an example:

 binding = new Binding()
 {
    Source = dataGrid.Columns[col],
    Path = new PropertyPath("ActualWidth"),
    Mode = BindingMode.OneWay, 
 };

 colDef.SetBinding(WidthProperty, binding);

I have tried other variations (e.g. ElementName = "DataGridColumn1", Path = new PropertyPath(“ActualWidth”) but get either no error (and no binding) or a 'cannot find source for binding' error or a BindingExpression path error.

There must be a way to set the binding in code…?

Best Answer

I found the answer. This line:

 colDef.SetBinding(WidthProperty, binding);

should be changed to:

 colDef.SetBinding(ColumnDefinition.WidthProperty, binding);
Related Topic