Bill M
Bill M

Reputation:

How can I bind WPF Grid Column Width in code?

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...?

Upvotes: 4

Views: 9735

Answers (3)

In my project I do like this - thought it was worth mentioning, since I had a lot of problems making it work before I got it:

    DataGridTextColumn c = new DataGridTextColumn
    {
          // Binding to my value (not directly related to the question)
          Binding = new Binding
          {
               Path = new PropertyPath(cd.Title + ".Value"),
               Mode = BindingMode.TwoWay
          }
     };

     // Binding the width 
     BindingOperations.SetBinding(c, DataGridTextColumn.WidthProperty, new Binding
     {
           Source = cd,                        // An INotifying object
           Path = new PropertyPath("Width"),   // A Property of that object
           Mode = BindingMode.TwoWay
      });

Upvotes: 0

GuYsH
GuYsH

Reputation: 313

DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Width = DataGridLength.SizeToHeader;

Google DataGridLength to get other options....

Upvotes: 0

Bill M
Bill M

Reputation:

I found the answer. This line:

 colDef.SetBinding(WidthProperty, binding);

should be changed to:

 colDef.SetBinding(ColumnDefinition.WidthProperty, binding);

Upvotes: 6

Related Questions