Search code examples
mvvminotifypropertychangedpostsharp

Subscribe to propertyChanged event PostSharp


I have my ViewModel made with PostSharp:

[NotifyPropertyChanged]
class ProfileSelectorViewModel
{
    public int Selection { get; set; }

}

Selection is bound to the selection property of a listbox. How can I subscribe to the change of this property? I want to call a method when Selection changes it's value.


Solution

  • You can subscribe to the PropertyChanged event by casting an object of ProfileSelectorViewModel class. Because your tooling may complain that the class does not implement the interface INotifyPropertyChanged yet, you can use a helper method Post.Cast<SourceType, TargetType>(SourceType).

    So if you have an object obj of type ProfileSelectorViewModel and a method OnSelectionChanged handling the change, the subscription looks like this:

    Post.Cast<ProfileSelectorViewModel,INotifyPropertyChanged>(obj).PropertyChanged += OnSelectionChanged;
    

    See http://doc.postsharp.net/inotifypropertychanged-add#consuming for details.