DataContext绑定 [英] DataContext binding
问题描述
我有三种不同的看法。我有每个视图的视图模型。我要做的是将视图的数据上下文设置为相应视图模型的新实例,如下所示:
What I have is three different views. I have view models for each of these views. What I do is set the datacontext of the view to a new instance of the respective view model and this works like shown below:
public LoginScreen()
{
InitializeComponent();
DataContext = new LoginScreenViewModel();
}
此功能可以按需运行。
This works as desired. Everything binds correctly and such.
现在,我将每个视图设置为UserControls。我的Window的每个视图都有数据模板,如下所示:
Now, I have each of my views set up as UserControls. I have my Window that has datatemplates for each of my views as shown below:
<Window.Resources>
<DataTemplate DataType="{x:Type vm:LoginScreenViewModel}">
<v:LoginScreen/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
<v:MainWindow/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutScreenViewModel}">
<v:AboutScreenView/>
</DataTemplate>
</Window.Resources>
我这样显示视图:
<Grid>
<ContentControl Content="{Binding CurrentView}"/>
</Grid>
这允许我在窗口的视图模型中创建视图模型,将其设置为CurrentView并与之关联该视图模型将显示在窗口中。
This allows me to create viewmodels in my window's view model set them as the CurrentView and the view associated with that view model is displayed in the window. This all works correctly.
我的问题是,如果我切换视图,则存储在View的ViewModel中的所有信息都会被破坏。我的问题是,如何将每个视图的数据上下文绑定到正在创建它的视图模型,而不是绑定到后面的代码中的新实例?
My problem is that if I switch views, all of the information that is stored in a View's ViewModel is destroyed. My question is, how to I bind the datacontext of each view to the viewmodel that is creating it instead of to a new instance in the code behind?
推荐答案
我认为您在这里有些困惑。您无需为视图
显式创建 DataContext(s)
。当您的 ViewModel
定义您的视图时,它也被向下传递到 View
,因为它是 DataContext
。
I think you are a little confused here. You don't need to create DataContext(s)
for your views
explicitly. When your ViewModel
define your View It is also passed down to your View
as it's DataContext
.
不要明确分配
DataContext
请尝试在加载视图后检查视图的
DataContext
。ViewModel
实际上是导致view
加载的原因。
Don't assign a
DataContext
explicitly and try check theDataContext
of a view after it is loaded. It will be theViewModel
that actually caused theview
to load.
例如,如果您的视图为 LoginScreen
,则您的DataContext将为 vm:LoginScreenViewModel
。您无需在加载LoginScreen并将其分配给视图之后创建 vm:LoginScreenViewModel
的新对象。
For example if your view is LoginScreen
your DataContext will be vm:LoginScreenViewModel
. you don't need to create a new object of vm:LoginScreenViewModel
after LoginScreen is loaded and assign it to view.
这篇关于DataContext绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!