I'm making multiple DataGrids in an application with the same set of columns and bindings. What I'm hoping to do is make all the DataGrid respond appropriately to a change in one DataGrid. If I change the size of one column, the corresponding columns in the other DGs should have the same width. It's somewhat similar to this question on S.O. (WPF share column width between separate grids) except for DataGrids, not Grids. I was hoping DataGrids would have a property similar to IsSharedSize like in Grid but this doesn't seem to be the case.
Is there a property I could access, or some alternative approach, to do what I'm trying to accomplish? Before anyone proposes this though, I cannot merge them all into one DataGrid, what I'm attempting means I can't put all the information in one DataGrid due to the nature of the application itself.
While sharing width is not possible in DataGrid's
out-of-the-box, this is what I came across as the best way to handle such scenarios.
Create bindings between the source DataGrid
columns and the target DataGrid
columns widths. In my case I have two target DataGrid's
(dgTarget1 and dgTarget2), so here is the code:
for (int index = 0; index < dgSource.Columns.Count; index++)
{
Binding bindingWidth = new Binding();
bindingWidth.Mode = BindingMode.TwoWay;
bindingWidth.Source = dgSource.Columns[index];
bindingWidth.Path = new PropertyPath(DataGridColumn.WidthProperty);
BindingOperations.SetBinding(dgTarget1.Columns[index], DataGridColumn.WidthProperty, bindingWidth);
BindingOperations.SetBinding(dgTarget2.Columns[index], DataGridColumn.WidthProperty, bindingWidth);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With