【问题标题】:Disable the built in descending sorting of the wpf DataGrid control禁用 wpf DataGrid 控件的内置降序排序
【发布时间】:2013-04-23 14:03:03
【问题描述】:

我正在使用 WPF 数据网格,需要让用户仅按升序对列进行排序,而不允许降序。

有没有简单的方法可以做到这一点?

简单的方法是使用集合视图源实现我自己的排序,并在列标题上监听鼠标单击事件。

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    您也可以使用行为来获得它。因为在这种情况下使用行为会更好。

    这就是你要做的:

    首先将 SortOnlyAscending.cs 类添加到您的项目中。

    public class SortOnlyAscending:Behavior<DataGrid> 
    {
        protected override void OnAttached()
        {
            AssociatedObject.Sorting += AssociatedObject_Sorting;
            base.OnAttached();
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.Sorting -= AssociatedObject_Sorting;
            base.OnDetaching();
        }
    
        private void AssociatedObject_Sorting(object sender, DataGridSortingEventArgs e)
        {
            e.Column.SortDirection = ListSortDirection.Ascending;
        }
    }
    

    然后在 .xaml 中,您将像这样将此行为添加到您的 DataGrid 中:

       <DataGrid>
            <i:Interaction.Behaviors>
               <local:SortOnlyAscending/>
            </i:Interaction.Behaviors>
       </DataGrid>
    

    此外,您还必须在 .xaml 中添加两个名称空间以使用您的行为。我的项目名称是 WpfApplication1,所以你可以随意更改它。

     xmlns:local ="clr-namespace:WpfApplication1" 
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    就是这样。您还需要 System.Windows.interactivity.dll 来使用 Behavior 类。 您也可以从 NUget Package Manager 下载它。这里是link

    【讨论】:

      【解决方案2】:

      好的,我明白了……

      只处理DataGrid的排序事件:

       private void DataGrid_OnSorting(object sender, DataGridSortingEventArgs e)
          {
              e.Column.SortDirection = ListSortDirection.Ascending;
          }
      

      【讨论】:

        猜你喜欢
        • 2014-05-29
        • 2016-09-18
        • 2013-04-24
        • 2013-12-31
        • 1970-01-01
        • 1970-01-01
        • 2011-09-04
        • 2016-04-29
        • 1970-01-01
        相关资源
        最近更新 更多