Search code examples
wpfeventspropertychanged

Debugging PropertyChanged


I have a class named ViewModel, with this code:

public event PropertyChangedEventHandler PropertyChanged;

var copyOfPropertyChangedEvent = PropertyChanged;

if (copyOfPropertyChangedEvent != null)
{
    var args = ViewModel.GetPropertyChangedEventArgs(propertyName);
    copyOfPropertyChangedEvent(this, args);
}

When I debug this, I want to see what's going on in the copyOfPropertyChangedEvent event. When I press on F12, it takes me to the line: var copyOfPropertyChangedEvent = PropertyChanged; When I search for all of the usages of PropertyChanged, Visual Studio gives me a few usages and when I put breakpoint inside all of them, none of them are hit.

How can I see what is going on in the PropertyChanged event?


Solution

  • Okay, we will try speculation then :)

    First off I would implement it the following way, as R# does.

    public class YourViewModelBase : INotifyPropertyChanged
    {
       public event PropertyChangedEventHandler PropertyChanged;
    
       [NotifyPropertyChangedInvocator] // remove if no R#
       protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
       {
           PropertyChangedEventHandler handler = PropertyChanged;            
           if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
       }
       // .....
    }
    

    Now I'm sure you know that an event contains a list of methods to invoke. PropertyChanged is used by the framework to signal the GUI that a reevaluation of the property in question must be performed(bindings, run converters etc and then redraw), and you can also hook yourself onto it. If it's null, then maybe the UI isn't hooked on - that's why I ask for more information there. It is part of the INotifyPropertyChanged Interface, as you are aware :)

    Anyways, if you are just curious on how it works internally, you may install RedGate Reflector, which will allow you to step into any non-native code. Or you may diassemble System.dll and trace it there.

    Hope it helps,

    Cheers

    Stian