GrayDS
GrayDS

Reputation: 363

Commands across View-Models

I am working on my first WPF/MVVM application, and I have come across a limitation in my knowledge of commands!

Here is my scenario.

I have a window - Customer.xaml.

It houses 2 usercontrols

Each of THOSE has it's own view model.

So, the hierarchy looks like this:

... Customer.xaml

... ... viewCustomerSearch.xaml

... ... ... viewmodelCustomerSearch.xaml

... ... viewCustomerDetails.xaml

... ... ... viewmodelCustomerDetails.xaml

I understand this to be a 'not uncommon' scenario.

For what it is worth, the user selects a customer by double clicking on a listview line in the viewCustomerSearch.xaml control.

The problem is: I now need to tell the viewmodelCustomerDetails.xaml class which customer the user has just selected. I cannot work this out at all.

Does anyone have any help on where I declare the command I need, how it gets hooked up, where the implementation code fires, etc?

Any help gratefully appreciated, DS

Upvotes: 0

Views: 240

Answers (2)

Phil
Phil

Reputation: 43011

Alternatively, if you don't need completely decoupled view-models, then your Customers.xaml could set its DataContext to an instance of CustomersViewModel. The search view would inherit this data context, would bind it's list view to the list of customers, and would set the SelectedItem property in response to a double click. The detail view DataContext would be bound to the SelectedItem property.

public class CustomersViewModel : ViewModelBase
{
    public Customer SelectedItem
    {
        get { return _selectedItem; }
        set { Set(() => SelectedItem, ref _selectedItem, value); }
    }

    private Customer _selectedItem;
    public IEnumerable<Customer> Customers { get; private set; }
}

public class Customer : ViewModelBase
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { Set(() => Name, ref _name, value); }
    }
    ...
}

Upvotes: 0

devdigital
devdigital

Reputation: 34369

Typically, to do inter-viewmodel communication, you can either:

  1. Use standard .NET events, and use the parent view model as the mediator - in your case the Customer view model would have references to the 2 child view models, and can subscribe to events, and call appropriate methods on the child view models when the events are published
  2. Use an event aggregator pattern

Frameworks such as Caliburn.Micro and Prism provide an implementation of the event aggregator pattern.

Upvotes: 4

Related Questions