tags:

views:

62

answers:

2

Hi All,

I am new in MVVM and WPF. so be easy with me.

I have a model (model A) in MVVM, in the ViewModel I have a collection. The collection is present in the View as ListView. I have another model (model B - not ui model) that need to do something every time that the listview is changing.

How can I alert model B on the selection change? What will be the right way?

  • By event that model A (ViewModel) will fire, and model B will catch?
  • By attached property of model A?
  • By notify property change?
  • By sending relay commands from model B to model A?
+1  A: 

Use Publish /Subscriber pattern

Personally I would send the commands from VM to VM and make them update the Model

hope this helps

server info
I prefer no to add outside toolkits like the messenger or unity.Commands sounds good.But then I still have the question, How to pass the selection change from the View to the ViewModel? By code in the View, or is there another (cool) way?
AmirE
@AmirE: Hope your ListView is bound to Collection in the ViewModel. Similarly you have to bind the SelectedItem property in the View to a property in the ViewModel so that you would get the item selected without any additional notifications.
Veer
@AmirE If you not like frameworks that's fine Puplish/Subscriber as well as Observer are just patterns to guide you to decouple eventing. They just did already the pluming... Look also for Triggers (since you are not on silverlight) and Behaviors which fires Commands -> ICommand
server info
OK, Thank you very much :)
AmirE
+1  A: 

I would either

  1. Expose an event in ViewModel A that ViewModel B can subscribe to. I would then raise that event anytime the selection changes.
  2. Leverage INotifyPropertyChanged for notification to ViewModel B

I prefer option 1 because it makes it more obvious what you're trying to do. Plus it's more efficient (you don't have code smell of filtering on which property changed and then doing some action.)

IMHO I think relay commands should only be used as an interface between a view and a viewmodel to aid in a separation of concerns. But when you're programming from a class to a class, just use standard OOP conventions.

so pseudo code would probably look like this:

public class ViewModelA
{
  public event EventHandler SelectedObjectChanged;

  public IList<MyObject> ObjectList {get;set;}
  public MyObject _SelectedObject;
  public MyObject SelectedObject
  {
    get { return _SelectedObject;}
    set 
    { 
      _SelectedObject = value; 
      if (SelectedObjectChanged != null) 
        SelectedObjectChanged(value); 
    }
  }
}
Jose