Suppose we have a simple class with two string properties, implementing 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;
}
Let's create an ObservableCollection of these and assign them to a 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"));
}
Then, using MVVM we bind this up in our XAML:
<sdk:DataGrid ItemsSource="{Binding Path=MyItems}" />
If we then go in and edit one of the categories, say changing one of the "C"s to "A" for example, the gridview handles it brilliantly. It maintains collapse status of groups, and even adds new group headers if needed!
The problem occurs when we change the category programmatically in the viewmodel (or, for example, from within another gridview bound to the same data). In this case, the category text will updated, but the item will not move into the new appropriate group, new groups will not be created, row headers will not be updated, etc.
How can I trigger the gridview to update its groups when the property is changed outside of the gridviews editing capabilities?
Any workaround is welcome, however triggering a simple Refresh() is not as that will wipe out scrolling/collapsing/etc.
You need to wrap the edit with EditItem() and 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);