【问题标题】:Sort DataGrid Rows After Removing Grouping through XAML通过 XAML 删除分组后对 DataGrid 行进行排序
【发布时间】:2019-01-10 12:02:52
【问题描述】:

总结:删除分组后,数据网格中的项目排序。

所以我目前有一个带有用户控件的项目,该控件根据数据类型显示两个控件之一。现在,当该控件是 DataGrid 时,我在模板上设置了使用分组的样式。

<!--STYLE used to add grouping & expanders to data grid-->
  <Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
     <Setter Property="Template">
        <Setter.Value>
           <ControlTemplate TargetType="{x:Type GroupItem}">
              <Expander IsExpanded="False" >
                 <Expander.Header>
                    <TextBlock Text="{Binding Name}" TextDecorations="Underline"/>
                 </Expander.Header>
                 <ItemsPresenter/>
              </Expander>
           </ControlTemplate>
        </Setter.Value>
     </Setter>
  </Style>

它是这样在模型中设置的,因此分组是在一个名为“Group”的属性上完成的。

Data = new ListCollectionView(rows);
Data.GroupDescriptions.Add(new PropertyGroupDescription("Group"));

现在用户可以切换一个切换按钮来删除标题,因此只显示一个值列表。

public bool IsGrouped
{
   get { return isGrouped; }
   set
   {
      isGrouped = value;
      OnPropertyChanged();
      if (ConfigurationModel != null)
      {
         if (IsGrouped == true)
            (ConfigurationModel as ConfigurationKeyPairModel).AddGrouping();
         else
            (ConfigurationModel as ConfigurationKeyPairModel).RemoveGrouping();
      }
   }
}

public void RemoveGrouping()
{
   if(Data.GroupDescriptions.Count > 0)
      Data.GroupDescriptions.RemoveAt(0);
}

public void AddGrouping()
{
   if(Data.GroupDescriptions.Count < 1)
      Data.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
}

删除分组后,项目将返回到您期望的普通数据网格。但如果他们被分组,他们仍然处于相同的位置。我不想让用户手动单击列标题(无论如何都是隐藏的)我想让这些数据立即自行排序。在过去的一个小时里,我环顾四周,但没有找到任何像 MVVM 或不只是让用户单击列标题的体面的解决方案。

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    您可以通过将SortDescription 添加到其SortDescriptions 属性来按属性对CollectionView 进行排序:

    public void RemoveGrouping()
    {
        if (Data.GroupDescriptions.Count > 0)
            Data.GroupDescriptions.RemoveAt(0);
        Data.SortDescriptions.Clear();
        Data.SortDescriptions.Add(new SortDescription("PropertyName", ListSortDirection.Ascending));
    }
    

    如果没有添加SortDescriptions,则排序顺序实际上是未定义的。

    【讨论】:

    • 谢谢,不知道我是怎么错过的,但我认为看到大多数使用 XAML 版本的 CollectionView 的帖子让我感到震惊。谢谢!
    猜你喜欢
    • 2014-12-12
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2022-01-22
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多