-1

I'm working on a WPF application. This application features a main window (main view) that is 'databind-ed' to a main view model. This main view is what instantiates the main view model.

Within this main window, sub views (i.e. usercontrols) are programmatically created. The main window features a dropdown lists that allows users to select different views. Each usercontrol view has a corresponding view model.

When a user selects a dropdown option, this triggers a new view model to be created. I then use data templating to template the view model to an instance of the associated view as shown below:

      <DataTemplate DataType = "{x:Type ViewModels:MyViewModel}">
           <Views:MyView />
      </DataTemplate>

My question: How do I go about data binding 'MyView' to 'MyViewModel'? I'm assuming I need to add an appropriate datacontext to MyView.xaml, however, I don't know how to do this given the fact that 'MyView' is not creating an instance of 'MyViewModel'. I essentially want to databind my view to a previously existing view model. Any ideas?

EDIT: It turns out that my view automatically databinds to my view model's data template. However, I'm unsure why this just magically works. What's going on here?

Izzo
  • 4,461
  • 13
  • 45
  • 82
  • It's not magic. It's how WPF is _designed_ and _documented_. When WPF maps the template to your view model object, it necessarily has your view model object reference, and it simply sets the `DataContext` of the top-level element of your template to that view model. It is actually quite simple, a lot simpler than the work WPF has to go to in order to actually _find_ the template you're using in the first place (why don't you think _that_ part is magic?). – Peter Duniho Aug 16 '17 at 01:56

1 Answers1

0

you have to bind your viewmodel with contentcontrol. Like this.

<ContentControl DataContext="{Binding ViewModels}" Content="{Binding Path=CurrentlySelectedComboBoxViewModel}">
  <ContentControl.Resources>
     <DataTemplate DataType="{x:Type vm:TypeAViewModel}">
        <StackPanel>
           <local:TypeAUserControl />
           </StackPanel>
     </DataTemplate>

     <DataTemplate DataType="{x:Type vm:TypeBViewModel}">
        <StackPanel>
           <local:TypeBUserControl />
        </StackPanel>
     </DataTemplate>
  </ContentControl.Resources>
</ContentControl>
Joby James
  • 429
  • 8
  • 22