AmirE
AmirE

Reputation: 11

MVVM question, Event fire in the View

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?

Upvotes: 1

Views: 452

Answers (2)

server info
server info

Reputation: 1335

Use Publish /Subscriber pattern

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

hope this helps

Upvotes: 1

Jose
Jose

Reputation: 11091

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); 
    }
  }
}

Upvotes: 1

Related Questions