Vineet v
Vineet v

Reputation: 175

Accessing MainViewModel from another viewmodel

I've a question on VM communication.

Here's my code in C#/WPF app.On my MainWindow.xam,I've a button. On click of this button, I need to access and modify the ProductList collection from within another ViewModel. How do I achieve this please?

public List<ProductInfo> ProductList { get; private set; }

private MainWindow m_mvWindow = null;

public MainWindowViewModel(MainWindow window)
{
    this.m_mvWindow = window;
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainWindowViewModel(this); 
    }
}

Thanks.

Upvotes: 1

Views: 3773

Answers (2)

Sefe
Sefe

Reputation: 14007

You can use either of these ways:

  1. Create an event in the other view model and handle it in the main view model. That would be the preferred way, since it does avoid coupling your child VM to the main VM, which is poor design.
  2. Pass the collection to the child VM in a constructor. Try to avoid passing the full main VM, again to avoid coupling.

Upvotes: 0

Barracoder
Barracoder

Reputation: 3764

The simplest solution would be to expose your other VM as a property of MainWindowViewModel, pass the child VM a reference to the ProductList collection and have an ICommand on the child VM which is bound to the button in your XAML and which handles the collection modifications.

Something like this:

Main VM

public class MainViewModel
{
   <!-- Your stuff ->
   public ChildViewModel ChildViewModel
   {
      if(_childViewModel == null)
      { 
         _childViewModel = new ChildViewModel(ProductList)
      }
      return _childViewModel;         
   }
}

Child VM

public class ChildViewModel
{
   private List<ProductInfo> _products;

   public DelegateCommand ClearCollection {get; set;}

   public ChildViewModel(List<ProductInfo> products)
   { 
      _products = products;
      ClearCollection = new DelegateCommand(OnClearCollection);
   }

   private void OnClearCollection()
   {
      _products.Clear();
   }
}

And in the xaml...

<Button Command={Binding ChildViewModel.ClearCommand} Content="..." />

Upvotes: 2

Related Questions