假设我们有一个带有两个字符串属性的简单类,实现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可以很好地处理它。它维护组的崩溃状态,甚至在需要时添加新的组头!
当我们在viewmodel中以编程方式更改类别时(或者,例如,从绑定到相同数据的另一个gridview中)更改类别时,会出现问题。在这种情况下,类别文本将更新,但该项目不会移动到新的相应组中,不会创建新组,不会更新行标题等。
如果在网格视图编辑功能之外更改属性,如何触发gridview更新其组?
欢迎使用任何解决方法,但触发简单的Refresh()并不会消除滚动/折叠/等。
答案 0 :(得分: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);