【问题标题】:Two datagrids with same sorting wpf具有相同排序wpf的两个数据网格
【发布时间】:2020-04-08 19:24:43
【问题描述】:

我有两个作为 itemsource 绑定到两个数据表的数据网格 Datagrids。我希望能够在单击其中一个标题时对两个数据网格列进行排序。当属性:"CanUserSortColumns="True"" 设置为 true 时,数据网格不会一起排序。我想要的是当单击列标题时,来自 datagrid 1 或 datagrid 2 的行将遵循排序,因此该行与排序匹配。

我已经研究了这个 abit 并看到 dataviewer 可以用于排序(因为它绑定到数据表),还看到可以使用 CollectionView,但我看不到任何使用两个数据网格执行此操作的示例,只有与一个。

只排序一个数据网格(我有什么): Image of what I have

通过单击标题对两个数据网格进行排序(我需要什么): Image of what i need

有这样做的原因吗?两个数据网格具有相同的行数。

【问题讨论】:

  • 您需要两个表中有一个公共字段,以便您可以使用 JOIN。然后要获得一张表,请使用 JOIN。否则,您必须为每个表分配一个行号,然后按行号加入。

标签: c# wpf sorting datagrid


【解决方案1】:

这是一个可以帮助您的附加属性,我只是对其进行了快速而肮脏的编码,因此我认为您可以确保我在使用之前没有忘记任何东西(如果我忘记了,请编辑答案)。您可以在 XAML 中以这种方式使用它:

<DataGrid local:DatagridBehaviour.SyncSortingWith="{Binding ElementName=otherDataGrid}"/>
<DataGrid Name="otherDataGrid"/>

附加属性:

public static class DatagridBehaviour
{
    public static DataGrid GetSyncSortingWith(DependencyObject obj)
    {
        return (DataGrid)obj.GetValue(SyncSortingWithProperty);
    }

    public static void SetSyncSortingWith(DependencyObject obj, DataGrid value)
    {
        obj.SetValue(SyncSortingWithProperty, value);
    }

    public static readonly DependencyProperty SyncSortingWithProperty = DependencyProperty.RegisterAttached("SyncSortingWith", typeof(DataGrid), typeof(DatagridBehaviour), new PropertyMetadata(OnSyncSortingWithChanged));

    private static void OnSyncSortingWithChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is DataGrid source)
        {
            source.Sorting -= DataGridSorting;
            if (e.NewValue is DataGrid other)
            {
                other.Sorting += DataGridSorting;
                source.Sorting += DataGridSorting;
            }

            if (e.OldValue is DataGrid previous)
            {
                previous.Sorting -= DataGridSorting;
            }
        }
    }

    private static void DataGridSorting(object sender, DataGridSortingEventArgs e)
    {
        if (sender is DataGrid dataGrid)
        {
            DataGridColumn column = dataGrid.Columns[0];
            dataGrid.Items.SortDescriptions.Clear();
            dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending));

            // May not be needed
            dataGrid.Items.Refresh();
        }
    }
}

唯一需要它工作的就是在两个数据网格的列上具有相同的绑定路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多