简体   繁体   English

使用MVVM在XAML / WPF中的导航上设置视图的DataContext

[英]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. 在我的WPF应用程序中,我在一个主窗口中有多个视图,并且我试图在这些视图之间实现导航。 My Problem is that i can't set the DataContext attribute of the views. 我的问题是我无法设置视图的DataContext属性。 My MainWindowViewModel: 我的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: 我的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). 因此,主要思想是CurentViewModel显示当前导航在哪个View上(DataTemplate显示与ViewModel相对应的View)。 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. 问题在于所显示的视图没有获取DataContext(因此MainWindowViewModel的属性mainScreenViewModel / levelViewModel),它创建了ViewModels的新实例。 Is it possible to hand over the properties as a DataContext to the View from the DataTemplate? 是否可以将属性作为DataContext从DataTemplate移交给View? Thanks for your help! 谢谢你的帮助!

The Content property contains Content属性包含

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 相反,您需要将其绑定到包含以下内容的DataContext属性:

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 这意味着您的代码几乎是正确的,只需更改CurrentViewModel的绑定即可

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

to get your code to work. 使您的代码正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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