0
votes

I am working on an WPF MVVM application. I want some kind of event should fires when the collection that is bind to my datagrid changes.

Ex:- My datagrid item source is ObservableCollection UserList

I want when i clear UserList collection, some event fires on datagrid to notify itself. I've tried this event DataContextChanged of datagrid, but it didn't help.

Please guide

Thanks

4
Use bindings instead of code behind itemsource settingsRumplin

4 Answers

1
votes

If you are following the MVVM pattern you should not need to handle UI events. Your collection of objects is part of your ViewModel, therefore you should add a PropertyChanged event on your ViewModel that fires when the collection is changed.

0
votes

If you are using MVVM, then you have a property like this

        /// <summary>
    /// The <see cref="UserList" /> property's name.
    /// </summary>
    public const string UserListPropertyName = "UserList";
    private ObservableCollection<UserList> _userList = new ObservableCollection<UserList>();
    public ObservableCollection<UserList> UserList
    {
        get
        {
            return _userList;
        }
        set
        {
            if (_userList != value)
            {
                _userList = value;
                RaisePropertyChanged(UserListPropertyName);
            }
        }
    }

And in the setter part you can call any method in the view model, if you are using code behind, then you are not using MVVM pattern

0
votes

If you want an event that fires when the reference to the collection changes, then you should be using and OnPropertyChanged event in your ViewModel as Rumplin has demonstrated. If however you want to know when a User is added to the collection or removed from the collection, then you need to add a handler for the CollectionChanged event on the ObservableCollection.

0
votes

The event you're looking for is CollectionChanged.

A source of confusion for you (and others who try to do the same thing) is that you're thinking that when the collection changes, the source of your data grid has changed. Not so. The ItemsSource of the data grid is still the collection - you haven't assigned it to a different collection, or cleared it. So PropertyChanged and DataContextChanged are not being raised, and handling them has no effect here.

Note that CollectionChanged is pretty involved, because a lot of things constitute changes to a collection, so you're going to need to understand it pretty thoroughly to handle it correctly. I suspect that you don't really need to handle it - that you're trying to do something with events that can better be done through binding.