1
votes

I have a C# project in WPF. I've worked with MVC before and I am now trying to get around with MVVM in combination with XAML.

I have multiple models, I have one GUI Window with Tabitems, and I have multiple ViewModels. Each tab item is related to each model, therefore I have a ViewModel for each model.

Now I want to use binding (why else use WPF/XAML). How do I bind a button to a command in ViewModel X?

E.g.:

  • Two Models: house and person
  • View: Two TabItems in the GUI, one TabItem about all interaction with houses, and one TabItem for persons.
  • Two ViewModels, correlating with each TabItem.
  • I have a command to put a house for sale.

I see alot of code that just binding to the name of the command, but since I have multiple views, and not just 1, how do I do it? Should I create 1 ViewModel that will handle all other ViewModels?

2
Can't believe how complicated it is to bind to the RoutedCommand of an instance of a viewmodel....Mike de Klerk
1. Yes, create one parent viewmodel that contains the others as child properties. 2. You can use tiered namespaces like ParentViewModel.ChildViewModel1.MyCommandXcalibur37

2 Answers

1
votes

I see alot of code that just binding to the name of the command, but since I have multiple views, and not just 1, how do I do it?

Make sure you understand how the binding system works. You're binding to a DataContext. So, if each individual tab has a separate DataContext value set, then you can bind using the name of the command.

Knowing this, you can proceed using the pattern you've established. In my humble opinion, I think it will get much too complicated. Majority of MVVM developers are applying a one-to-one relationship with the View to ViewModel (things get tricky when talking about UserControl objects though). Nothing is set in stone though, so ultimately it's up to you on how you want to proceed.

0
votes

I guess you have limited number of viewmodels. So you have 2 choises: first, is to use DataTemplateSelector, and the second is to define in xaml each TabItem view and Bind each Content to necessary VM.