在 WPF 中设置子 UserControl 的数据上下文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24472677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:01:35  来源:igfitidea点击:

Set datacontext of child UserControl in WPF

wpfwpf-controls

提问by Masood Alam

I am not able to set the datacontext of the UserControl (the UserControl is nested within other UserControl).

我无法设置 UserControl 的数据上下文(UserControl 嵌套在其他 UserControl 中)。

I have the below structure:

我有以下结构:

Views/ViewModels:

视图/视图模型:

MainControl <-> MainViewModel <br>
UserControlA <-> ViewModelA<br>
UserControlB <-> ViewModelB<br><br>
ViewModels:<br>

ViewModelBis a property of ViewModelAMainViewModel instantiates ViewModelAand ViewModelBin the ctor.

ViewModelBViewModelAMainViewModel 实例化的一个属性,ViewModelA并且ViewModelBctor.

Views:
MainControlcontains UserControlA, which in turn contains UserControlBMainControlassigns the ViewModelAas the datacontext ( This works as expected )

视图:
MainControlcontains UserControlA,它依次包含UserControlBMainControl将 分配ViewModelA为数据上下文(这按预期工作)

<!-- MainControl Xaml-->
<UserControl x:Name="MainControl">

<views:UserControlA DataContext="{Binding ViewModelA}" />

</UserControl>

In UserControlAi doing the same thing as in the MainControl, binding the datacontext of UserControlBto its ViewModelwhich is a property in the ViewModelAThis is not working as expected...

UserControlA我做与在相同的事情中MainControl,将数据上下文绑定UserControlB到它ViewModel的属性,ViewModelA这是不按预期工作...

   <!-- USerControlA Xaml-->
    <UserControl>
    .....
    .....

    <views:UserControlB DataContext="{Binding DataContext.ViewModelB}" /> 

   </UserControl>

回答by Stuart

Change the datacontext binding for UserControlB to:

将 UserControlB 的数据上下文绑定更改为:

<UserControl>
    <views:UserControlB DataContext="{Binding ViewModelB}" /> 
</UserControl>