title: How can I bind WPF Grid Column Width in code?
body: <p>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:</p>
  
  <pre><code>&lt;Grid.ColumnDefinitions&gt;
     &lt;ColumnDefinition Width="{Binding ElementName=dataGrid, Path=RowHeaderWidth}" /&gt;
     &lt;ColumnDefinition Width="{Binding ElementName=Column0, Path=ActualWidth}" /&gt;
     &lt;ColumnDefinition Width="{Binding ElementName=Column1, Path=ActualWidth}" /&gt;
     Etc.
  
  &lt;Controls:DataGrid BorderBrush="White"  ItemsSource="{Binding DataTable}"  
                     Name="datagrid1" Grid.Row="2" RowHeaderWidth="0"&gt;
  
      &lt;Controls:DataGrid.Columns&gt;
      &lt;Controls:DataGridTextColumn  Header="Included"  Width="50" x:Name="Column0" /&gt;
      &lt;Controls:DataGridTextColumn  Header="First" Width="100" x:Name="Column1" /&gt;
       Etc.
  </code></pre>
  
  <p>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.</p>
  
  <p>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:</p>
  
  <pre><code> binding = new Binding()
   {
      Source = dataGrid.Columns[col],
      Path = new PropertyPath("ActualWidth"),
      Mode = BindingMode.OneWay, 
   };
  
   colDef.SetBinding(WidthProperty, binding);
  </code></pre>
  
  <p>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.</p>
  
  <p>There must be a way to set the binding in code...?</p>