I've got two WPF Toolkit DataGrids
, I'd like so that when the user resizes the first column in the first grid, it resizes the first column in the second grid. I've tried binding the width of the DataGridColumn
in the second grid to the appropriate column in the first grid, but it doesn't work. I'd prefer to use all xaml, but I'm fine with using code behind as well.
<tk:DataGrid Width="100" Height="100">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn x:Name="Column1" Width="50"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
<tk:DataGrid Width="100" Height="100">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn x:Name="Column1Copy" Width="{Binding Path=ActualWidth, ElementName=Column1}"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
I also tried binding to Width
instead of ActualWidth
, but neither works.
Any help is greatly appreciated.
I tried this:
However, It looks like since
DataGridColumn
s do not derive fromFrameworkElement
but instead derive fromDependencyObject
, binding in this manner is not available.I did a quick solution to this to using a attached behavior, Inspired by Ahmed answer above.
XAML:
The Second DataGrids, header and cell width, is now syncronized with the first grid header width.
If you want to bind column Width property in XAML, in 2
DataGrid
's than you have to do the following.In the first
DataGrid
name theDataGridTextColumn
:In the second
DataGrid
add aDiscreteObjectKeyFrame
pointing to the above mentioned column as a resource, and use the followingBinding
toWidth
property on theDataGridTextColumn
you want to "link":You can use the
DataGrid
LayoutUpdated
method to manipulate other objects regarding the column widths.I found a solution to this problem, and an extra cool solution :-) You can download the WPF toolkit and get the code of the DataGrid. Once you have the code all you have to do is change the DataGridColumn class to inherit FrameworkElement instead of DependencyObject. Once you do so - you are left with only one problem, the DataContext of the column would not be initialized since the column is not part of the logical tree, adding it to the logical tree would solve this. You can do it like this: Where the OnColumnInitialization is: private void OnColumnInitialization(object sender, EventArgs e) {
AddLogicalChild(sender); } Now that it is part of the logical tree you have the same data context and you can use binding on the Width property. If all are bound to the same Width - you have a complete sync of the Width of your columns. This worked for me :-) Gili
Well, I don't think that it is possible using straight XAML, but I still feel like it should because
DataGridColumn
does derive fromDependencyObject
. I did find a way to do it programatically though. I'm not thrilled about it, but it works: