0

假设我们有一个具有两个字符串属性的简单类,实现 INPC:

 public class TestClass : INotifyPropertyChanged
    {
        private string _category;
        public string Category
        {
            get { return _category; }
            set { _category = value; NotifyPropertyChanged("Category"); }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }

        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

让我们创建一个 ObservableCollection 并将它们分配给 PagedCollectionView:

public PagedCollectionView MyItems { get; set; }

public void Test()
{
    var items = new ObservableCollection<TestClass>();
    items.Add(new TestClass { Category = "A", Name = "Item 1" });
    items.Add(new TestClass { Category = "A", Name = "Item 2" });
    items.Add(new TestClass { Category = "B", Name = "Item 3" });
    items.Add(new TestClass { Category = "B", Name = "Item 4" });
    items.Add(new TestClass { Category = "C", Name = "Item 5" });
    items.Add(new TestClass { Category = "C", Name = "Item 6" });
    items.Add(new TestClass { Category = "C", Name = "Item 7" });

    MyItems = new PagedCollectionView(items);
    MyItems.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
}
  • 请注意,我们还设置了类别分组

然后,使用 MVVM 我们将其绑定到我们的 XAML 中:

<sdk:DataGrid ItemsSource="{Binding Path=MyItems}" />

如果我们然后进入并编辑其中一个类别,例如将其中一个“C”更改为“A”,gridview 可以出色地处理它。它维护组的折叠状态,甚至在需要时添加新的组标题!

当我们在视图模型中以编程方式更改类别(或者,例如,从绑定到相同数据的另一个网格视图中)时,就会出现问题。在这种情况下,类别文本将更新,但项目不会移动到新的适当组中,不会创建新组,不会更新行标题等。

当属性在 gridviews 编辑功能之外更改时,如何触发 gridview 更新其组?

欢迎任何解决方法,但是触发简单的 Refresh() 不会消除滚动/折叠/等。

4

1 回答 1

1

您需要使用 EditItem() 和 CommitEdit() 包装编辑

        // The following will fail to regroup
        //(MyItems[3] as TestClass).Category = "D";

        // The following works
        MyItems.EditItem(MyItems[3]);
        (MyItems[3] as TestClass).Category = "D";
        MyItems.CommitEdit();

        // The following will also fail to regroup            
        //(MyItems[3] as TestClass).Category = "D";
        //items[3] = items[3];

        // fails as well, surprisingly
        //(MyItems[3] as TestClass).Category = "D";
        //TestClass tmp = items[3];
        //items.RemoveAt(3);
        //items.Insert(3, tmp);
于 2012-06-03T22:53:17.637 回答