是否可以将UserControl的DataContext绑定到属性 [英] Is it possible to Bind the DataContext of a UserControl to a property
问题描述
我有一个用户控件,我想在两个不同的上下文中使用.用户控件需要将其DataContext设置为由父视图/视图模型创建的适当ViewModel的实例.
I have a user control that I would like to use in two different contexts. The user control needs its DataContext set to an instance of an appropriate ViewModel that has been created by the parent view/viewmodel.
我希望有这样的东西:
<local:Child DataContext="{Binding ChildViewModel}"/>
其中ChildViewModel是页面绑定到的ViewModel的inpc样式的属性.
where ChildViewModel is a inpc-styled property of the ViewModel that the page is bound to.
这似乎不起作用.是否可以通过使用绑定来分配DataContext?
That doesn't seem to work. Is it possible to assign the DataContext by using Binding?
推荐答案
将ContentControl的内容绑定到子ViewModel可能更简单,如下所示:
It would probably be simpler to bind the Content of an ContentControl to your child ViewModel like this:
<ContentControl Content="{Binding ChildViewModel}" />
..然后有一个DataTemplate来应用您的local:Child视图,就像这样
..and then have a DataTemplate to apply your local:Child View, like this
<DataTemplate DataType="{x:Type local:ChildViewModel}">
<local:Child />
</DataTemplate>
这篇关于是否可以将UserControl的DataContext绑定到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!