Andreas
Andreas

Reputation: 200

How to access another control's viewModel

I have a CustomControl B, which uses a DataContext/MVVM (viewModelB). Now I want to bind one Property of my CustomControl to another control A (uses viewModelA as DataContext).

So I have two Ideas:

  1. Whenever PropA in viewModelA changes, I could directly update PropB in the viewModelB. But this creates a dependency between the viewModels, which seems ugly to me. Or is this a common way in the MVVM pattern and can't be avoided?

  2. As an alternative I could think of a dependency property on CustomControlB and wire it to CustomControlA's viewModel by a binding, something like that:

    <myControlB PropB={Binding ElementName=myControlA, Path=DataContext.PropA} />.

    So far so good, but the dependency property is defined on the view now. How should I visualize it?

    • a) Should I transfer the value (from the property wrapper) to viewModelB and bind to it from viewB's XAML code?

    • b) Or should I directly update the view from B's codeBehind? Would this be still a proper MVVM "style"?

Which of the options would you recommend?

regards

Andreas

Upvotes: 2

Views: 135

Answers (1)

Adi Lester
Adi Lester

Reputation: 25211

As long as ViewModelA doesn't actively update ViewModelB, there is no real coupling between the two viewmodels. What I mean is that if your main view model (which knows both viewmodels) is the one that wires up the binding, the view models are still loosely coupled.

So to me any of these are fine:

  • Bind directly to myControlA.DataContext.PropA from XAML
  • Have the MainViewModel register for ViewModelA's property changed event and modify ViewModelB's property as necessary. Here MainViewModel knows about the two view models, but they know nothing of each other.

Upvotes: 1

Related Questions