如何设置的DataContext从视图模型中的DataTemplate创建的视图 [英] How to set the DataContext for a View created in DataTemplate from ViewModel
问题描述
有这个问题了,但他们没有回答我的问题。
例如:
There are questions on this already, but they don't answer my question. For example:
<ContentControl.Resources>
<DataTemplate DataType="{x:Type Databinding:RedScreenViewModel}" >
<Databinding:RedScreen DataContext="{Binding}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type Databinding:BlueScreenViewModel}">
<Databinding:BlueScreen DataContext="{Binding}" />
</DataTemplate>
</ContentControl.Resources>
正如你可以看到我在尝试设置的DataContext的创建视图希望它会使用视图模型被用于创建它。但是,当我通过代码背后.. DataContext的总是空。我如何能实现我想要什么?
谢谢
As you can see I am attempting to set the DataContext for the created View hoping that it would use the ViewModel that was used to create it. But when I step through the code behind.. the DataContext is always null. How can I achieve what I want? Thanks
推荐答案
如果你定义了一个的DataTemplate
为您在这一个视图控制视图模型类,它会自动有设置为视图模型的DataContext
。
If you define a DataTemplate
for your ViewModel class with a View control in it, it will automatically have the DataContext
set to the ViewModel.
这应该工作方式:
<ContentControl.Resources>
<DataTemplate DataType="{x:Type Databinding:RedScreenViewModel}">
<Databinding:RedScreen />
</DataTemplate>
<DataTemplate DataType="{x:Type Databinding:BlueScreenViewModel}">
<Databinding:BlueScreen />
</DataTemplate>
</ContentControl.Resources>
这篇关于如何设置的DataContext从视图模型中的DataTemplate创建的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!