简体   繁体   中英

Notifying WPF DataGrid on changes

I have a DataGrid bound to the ICollectionView (with filter on). More specifically, I have set view.Filter = SomeFilteringFunction which uses public DateTime DateFrom { get... set... } property, also bound to the DatePicker .

Well, and now, when I change DatePicker , bound property DateFrom is correctly changed but the DataGrid is not obviously re-filtered.

What is the most right way how to notify DataGrid to update itself?

Thank you in advance!

James

You shouldn't be binding directly to the ICollectionView, rather you bind to the source collection, and then apply the filter to the ICollectionView returned by CollectionViewSource.GetDefaultView.

<DataGrid ItemsSource="{Binding MyCollection}" />
// should raise INotityPropertyChange.PropertyChanged
public ObservableCollection<Entity> MyCollection { get; set; }

MyCollection = new ObservableCollection<Entity>(ctx.EntitySet)); 
ICollectionView view = CollectionViewSource.GetDefaultView(MyCollection);
view.Filter = SomeFilteringFunction;

Then when the value of the DatePicker changes you need to tell the ICollectionView to update.

ICollectionView view = CollectionViewSource.GetDefaultView(MyCollection);
view.Refresh();

You can subscribe to the PropertyChanged event (which i assume you implemented on the class) and refresh the view in the handler:

var view = CollectionViewSource.GetDefaultView(Collection);
if (view != null)
{
    view.Refresh();
}

Not sure if there is a cleaner way, though, but i'm quite positive you need to make that Refresh call at one point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM