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


I found the answer. This line:

 colDef.SetBinding(WidthProperty, binding);  

should be changed to:

 colDef.SetBinding(ColumnDefinition.WidthProperty, binding);  


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

Google DataGridLength to get other options....


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »