Question Details

No question body available.

Tags

c# .net mvvm wpf

Answers (2)

August 14, 2025 Score: 1 Rep: 85,137 Quality: Medium Completeness: 60%

Option 0

A big view model. But not a parent view model

ie

public class MainPageVM
{
  public List customers; //bind to CustomersList XAML
  public Customer selectedCustomer; //bind to CustomerDetail XAML AND CustomersList if it has highlighting etc for selected item
  public MainPageVM()
  {
    //binding really should be in the View but for brevity..
    CustomersList.CustomerSelected += async id => this.selectedCustomer = this.customers.First(i=>i.id == id);
  }
}

The problem you run into with the parent view model which this avoids is that of you creating non-generic Controls, each with their own view model. eg CustomerList.

CustomerList sits uncomfortably between a control and a page. You can still have it, but instead of exposing its code behind or viewmodel, just have bindings of the Model classes like List customers and plain events like CustomerSelected

Hold all the state at the top and treat your User Controls like Controls rather than sub pages. This keeps your page viewmodels flat and the logic easy to follow.

August 14, 2025 Score: 0 Rep: 117 Quality: Low Completeness: 60%

My approach for a similar problem is probably somewhere between your option 1 and Ewan's answer. I have a "master" view model that represents the top-level view, and it contains references to child view models (corresponding to child objects of the top-level object in the model).

In your case, I think that would correspond to something like:

public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection Customers { get; }

public MainViewModel(IEnumerable customers) { Customers = new ObservableCollection(); foreach (var customer in customers) { Customers.Add(new CustomerViewModel(customer)); // Can have ref to this too } // etc. }

// etc. }

Then your view has some sort of container control, and it can have a data template to set up binding to properties on CustomerViewModel, and you can also have a Customer view with bindings on the same view model.

If you really need to, you could have the child view model have a back-reference to the main view model, but I think ideally most things would be represented through properties (and INotifyPropertyChanged) rather than explicitly-subscribed events.

ObservableCollection is better if you expect the collection to be changing while the view is open, but you could do some more basic IEnumerable or collection if it will be static.