简体   繁体   中英

Wpf event when DataContext is modified

You know how a TextBox will have its content modified when the DataContext changes (not replaced, just modified)? Well I want to be notified just like the UI is, with some sort of event on the DataContext. So far, I haven't found a way to do this, and I'm about to give up and simply subscribe to all the events on each INotifyPropertyChanged in my DataContext. I know there's the DataContextChanged / DataContextChanging in the Window class, but so far I either can't get it to work, or this only fires when the DataContext is replaced completely. Is there a way to do this?

Think about what is being asked. If any property changes on a data context a general event is to fire.

What process is available which can do that operation externally ?

Decentralized Solution

Properties do not provide a change notification unless they are manually programmed to do so themselves; hence why INotifyPropertyChange is the route to normally use.

Centralized Solution

Otherwise a separate manager will need to reflect off of the instance taking a snapshot of all the properties. Then on a timer the manager will poll the instance for a current snapshot and compare that one to the old snapshot. If a change is detected an event can be fired and the new snapshot replaces the old.


DataContextChanged event is only fired when the DataContext of the Window has changed completely (set to null, or a new instance, etc.). I believe you are down the correct path, and inside your ViewModel, you will need to subscribe to NotifyPropertyChanged . In the event handler, you can switch on the corresponding property like so:

private void OnNotifyPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch (e.Property)
    {
        case "Property1":
            break;
        case "Property2":
            break;
        case "Property3":
            break;
    }
}

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