0
votes

in my WPF-application i have multiple Views in a main window and i tried to implement a navigation between those. My Problem is that i can't set the DataContext attribute of the views. My MainWindowViewModel:

    public Class MainWindowViewModel
    {

     public MainScreenViewModel mainScreenViewModel { get; set; }
     public LevelViewModel levelViewModel { get; set; }

     public ViewModelBase CurrentViewModel
     {
         get { return _currentViewModel; }
         set
         {
            _currentViewModel = value;
            RaisePropertyChanged(nameof(CurrentViewModel));
         }
     }

     private AdvancedViewModelBase _currentViewModel;
    }

My MainWindow:

<Window.Resources>
    <DataTemplate DataType="{x:Type ViewModels:MainScreenViewModel}">
        <views:MainScreen  />
    </DataTemplate>
    <DataTemplate DataType="{x:Type ViewModels:LevelViewModel}">
        <views:LevelView />
    </DataTemplate>
</Window.Resources>
<Border>
    <StackPanel>
        <UserControl Content="{Binding Path=CurrentViewModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></UserControl>
    </StackPanel>
</Border>

So the main idea is that the CurentViewModel shows on which View the navigation is at the moment (the DataTemplate shows the coreponding View to the ViewModel). The Problem is that the shown View doesn't get the DataContext (so the properties mainScreenViewModel/levelViewModel of the MainWindowViewModel), it creates a new instance of the ViewModels. Is it possible to hand over the properties as a DataContext to the View from the DataTemplate? Thanks for your help!

1
It's kinda smelly for one VM to hold another VM. For it to expose a polymorphic CurrentViewModel property is arguably bad tooMickyD

1 Answers

0
votes

The Content property contains

An object that contains the control's content

This means it is not the correct property to bind the view model. Instead you need to bind it to the DataContext property which contains

The object to use as data context

Now the defined templates are selected by their type like defined in the resources.

This means your code is almost correct, just change the binding of the CurrentViewModel like

<UserControl DataContext="{Binding CurrentViewModel}"/>

to get your code to work.