Re-sort WPF DataGrid after bounded Data has changed

前端 未结 5 2163
眼角桃花
眼角桃花 2020-12-14 06:43

I am looking for a way to re-sort my DataGrid when the underlying data has changed.

(The setting is quite standard: Th

5条回答
  •  孤街浪徒
    2020-12-14 07:28

    I cannot see any obviously easy ways, so I would try an Attached Behavior. It is a bit of a bastardization, but will give you what you want:

    public static class DataGridAttachedProperty
    {
         public static DataGrid _storedDataGrid;
         public static Boolean GetResortOnCollectionChanged(DataGrid dataGrid)
         {
             return (Boolean)dataGrid.GetValue(ResortOnCollectionChangedProperty);
         }
    
         public static void SetResortOnCollectionChanged(DataGrid dataGrid, Boolean value)
         {
             dataGrid.SetValue(ResortOnCollectionChangedProperty, value);
         }
    
        /// 
        /// Exposes attached behavior that will trigger resort
        /// 
        public static readonly DependencyProperty ResortOnCollectionChangedProperty = 
             DependencyProperty.RegisterAttached(
            "ResortOnCollectionChangedProperty", typeof (Boolean),
             typeof(DataGridAttachedProperty),
             new UIPropertyMetadata(false, OnResortOnCollectionChangedChange));
    
        private static void OnResortOnCollectionChangedChange
            (DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
          _storedDataGrid = dependencyObject as DataGrid;
          if (_storedDataGrid == null)
            return;
    
          if (e.NewValue is Boolean == false)
            return;
    
          var observableCollection = _storedDataGrid.ItemsSource as ObservableCollection;
          if(observableCollection == null)
            return;
          if ((Boolean)e.NewValue)
            observableCollection.CollectionChanged += OnCollectionChanged;
          else
            observableCollection.CollectionChanged -= OnCollectionChanged;
        }
    
        private static void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
          if (e.OldItems == e.NewItems)
            return;
    
          _storedDataGrid.Items.Refresh()
        }
    }
    

    Then, you can attach it via:

    
      
     
    

提交回复
热议问题