且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:A DataGrid同步B DataGrid与columnWith和DisplayIndex

更新时间:2023-02-09 18:50:01

我花了一些时间找到好的方法,所以对于那些不想搜索的人:-)
谢谢您的帮助

I took some times to find the good approach, so for those who don't want search :-) Thank you for your help

private static Dictionary<DataGridColumn, DataGridColumn> ColumnCache = new Dictionary<DataGridColumn, DataGridColumn>();
private static void SynchronizeVerticalDataGrid(DataGrid source, DataGrid associated)
{
    associated.HeadersVisibility = source.HeadersVisibility & (DataGridHeadersVisibility.Row);
    associated.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;

    int sourceColIndex = 0;
    for (int associatedColIndex = 0; associatedColIndex < associated.Columns.Count; associatedColIndex++)
    {
        var colAssociated = associated.Columns[associatedColIndex];
        var colSource = source.Columns[sourceColIndex];
        sourceColIndex++;

        ColumnCache.Add(colSource, colAssociated);

        Binding binding = new Binding();
        binding.Mode = BindingMode.TwoWay;
        binding.Source = colSource;
        binding.Path = new PropertyPath(DataGridColumn.WidthProperty);
        BindingOperations.SetBinding(colAssociated, DataGridColumn.WidthProperty, binding);
    }

    source.ColumnDisplayIndexChanged += (sender1, e1) =>
        {
            var a = ColumnCache[e1.Column];
            a.DisplayIndex = e1.Column.DisplayIndex;
        };
}