WPF的DataGrid同步列宽 [英] WPF DataGrid Sync Column Widths

查看:317
本文介绍了WPF的DataGrid同步列宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个WPF工具包 DataGrid中,我想,这样当用户调整第一网格的第一列,它会调整第一列中第二个网格。我试着在第二个网格中的第一个网格相应的列绑定的的DataGridColumn 的宽度,但它不工作。我想preFER使用所有XAML,但我很好用code后面以及

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>

我也试过结合宽度而不是 ActualWidth的,但既没有工作。

I also tried binding to Width instead of ActualWidth, but neither works.

任何帮助是极大AP preciated。

Any help is greatly appreciated.

推荐答案

好吧,我不认为这有可能采用直板XAML,但我还是觉得它应该因为的DataGridColumn 并从的DependencyObject 派生。我没有找到一个办法做到这一点编程虽然。我不激动不已,但它的工作原理:

Well, I don't think that it is possible using straight XAML, but I still feel like it should because DataGridColumn does derive from DependencyObject. I did find a way to do it programatically though. I'm not thrilled about it, but it works:

DataGridColumn.WidthProperty.AddValueChanged(upperCol, delegate
{
    if (changing) return;
    changing = true;
    mainCol.Width = upperCol.Width;
    changing = false;
});
DataGridColumn.WidthProperty.AddValueChanged(mainCol, delegate 
{ 
    if (changing) return;
    changing = true;
    upperCol.Width = mainCol.Width; 
    changing = false; 
});

public static void AddValueChanged(this DependencyProperty property, object sourceObject, EventHandler handler)
{
    DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, property.OwnerType);
    dpd.AddValueChanged(sourceObject, handler);
}

这篇关于WPF的DataGrid同步列宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆