简体   繁体   中英

Set the DataContext of a View on a Navigation in XAML/WPF using MVVM

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM