Reputation: 5670
I have a simple form with datagrid and a button. Items in the datagrid are bound to ObservableCollection
of customers
. The customer
implements INotifyPropertyChanged
interface. Each customer has a deleted
property (type bool). I set a filter for the customers default view to filter out deleted customers based on the deleted
property. So far it works.
Then I add an event for the button that marks selected customer as deleted. The problem is the grid is not updated after setting selected_customer.deleted = true
. The deleted customer is still visible. The column bound to deleted
property updates correctly. To remove the customer from the grid, I have to manually call Refresh()
method of the customers default view.
Why is not the datagrid updated automaticaly when I use ObservableCollection
and the customer implements INotifyPropertyChanged
interface? How to make it update automatically?
Upvotes: 2
Views: 2701
Reputation: 9687
I assume you use a CollectionViewSource for filtering. Below code will subscribe to changes to Deleted property of customer and refresh the collectioviewsource when Deleted changes. Customers is an ObservableCollection of class Customer. Customer has a bool property called Deleted and implements INotifyPropertyChanged. InitAutoRefresh() should be called before populating Customers.
private void InitAutoRefresh(ObservableCollection<Customer> observableCollection, CollectionViewSource collectionViewSource)
{
observableCollection.CollectionChanged +=
(sender, e) =>
{
foreach(Customer newItem in e.NewItems)
{
newItem.PropertyChanged +=
(sender2, e2) =>
{
if (e2.PropertyName == "Deleted")
{
collectionViewSource.View.Refresh();
}
};
}
};
}
Call it before you populate the observable collection. If you declared your collectionViewSource in XAML you can use FindResource to get the instance.
InitAutoRefresh(Customers, FindResource("cvsCustomers") as CollectionViewSource);
Upvotes: 1