views:

42

answers:

1

I want to make a reusable UserControl as:

  • A VIEW with its own VIEWMODEL where is the logic data recovery
  • This UserControl (or View ?) has a button 'OK' to target a RELAYCOMMAND in his viewmodel
  • I'm hosting this 'UserControl' in another VIEW ('MainPage'), who, herself, has its viewmodel

My question is:
How can I target the properties of VIEWMODEL of my 'MainPage' with the values outlined by my UC ?

+1  A: 

As long as your user control is contained in your main page it will inherit the main pages view model. This is the default and it applies unless you explicitly change the data context through data binding or code.

If your user control binds to it own view model then you could let the main view model contain an instance of the child view model and expose it through a public property. Now you could set the data context of your user control by binding the DataContext property to the property on the main view model.

Finally if your child view model has a reference to the main view model then they will be able to communicate as needed.

Edit:

I'll try to setup a simple example:

First the view models:

public class MainPageViewModel
{

  public MainPageViewModel()
  {
     ChildViewModel = new ChildViewModel(this);
  }

  public ChildViewModel {get; private set; }

  public ICommand OkCommand { get { // return the command here }}
}

public class ChildViewModel
{
  private MainPageViewModel _parentViewModel;
  public ChildViewModel(MainPageViewModel parentViewModel)
  {
    _parentViewModel = parentViewModel;
  }

  // Returns the command from the main page view model
  public ICommand OkCommand { get { return _parentViewModel.OkCommand; } }

  // Other properties as well
}

Here we have the main view model that has the child view model as a property. The child view model exposes the OkCommand that returns the value from the main view model.

Now in your main page xaml you can do the following:

<uc:MyUserControl DataContext="{Binding ChildViewModel}" />

Here you insert your user control and set it's data context to the child user control view model.

Rune Grimstad
Thank you for your reply but... Do you offer me an example ?
Zorg