0
votes

I'm working on my first C#/WPF project (I'm a Java/Web developer with some Flex/As experience). The MVVM pattern seemed to be the way to go so I've started climbing the learning curve...

I'd like to know what's considered as the way to go to notify state modifications between related ViewModel objects.

Long story short, I have a UserControl containing a TreeView that is bound to a ReadOnlyCollection exposed by MyTreeViewModel.

SomethingViewModel implements INotifyPropertyChanged and generates an event when its 'IsSelected' property is changed.

MyTreeViewModel has an event handler attached to the PropertyChanged event of SomethingViewModel and updates a property that it manages called 'CurrentlySelectedElement'.

MyTreeViewModel also implements INotifyPropertyChanged and generates an event when its 'CurrentlySelectedElement' property changes.

Finally, I have an event handler in another ViewModel class that handles the selection change.

Is this a correct way of approaching this in C#/WPF?

Also, I'm not really fond of using property names with Strings in my event handling methods; It doesn't seem very refactoring friendly to me.. For now, I've dealt with this by exposing the property name as a static string, so that I can simply use the following in my event handler method:

if(SomeViewModel.PROPERTY_IS_SELECTED.Equals(e.PropertyName)) { ... }

Do you know a better alternative? I guess there should be a way of doing this but to be honest I didn't investigate that any further yet.

Thanks for your feedback!

1

1 Answers

1
votes

Check out the Event Aggregator pattern. There are quite a few implementations out there. If you're using a MVVM framework ( https://stackguides.com/questions/1280462/what-mvvm-framework-are-you-using, What framework for MVVM should I use? ), chances are it will contain an implementation as well.