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

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

问题描述

我有两个 WPF 工具包 DataGrids,我希望当用户调整第一个网格中第一列的大小时,它会调整第二个网格中第一列的大小.我尝试将第二个网格中 DataGridColumn 的宽度绑定到第一个网格中的相应列,但它不起作用.我更喜欢使用所有 xaml,但我也可以使用隐藏的代码.

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>

我也尝试绑定到 Width 而不是 ActualWidth,但都不起作用.

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

非常感谢任何帮助.

推荐答案

嗯,我不认为使用直接的 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天全站免登陆