在关于数据绑定和UserControls之前的question I had posted中,我遇到了设置简单属性的问题,这样我就可以改变颜色,大小等。肯特给了我一些很棒的指针,但效果很好。然后,我创作了一个新的UserControl,并使用他的建议,使其工作得很好。
现在我正在进行下一步 - 数据绑定命令。我目前的结构如下:
窗口 - 包含 - > UserControlB - 包含 - > UserControlA
现在,UserControlA中的数据绑定属性运行良好,我的UserControlB公开了这些相同的属性,以便Window可以间接更改UserControlA。问题是UserControlB的DataContext设置如下:
<UserControl x:Name="root">
<Grid DataContext="{Binding ElementName=root}">
...
<Button Command="{Binding MyCommand}" />
...
</Grid>
</UserControl>
但我希望MyCommand绑定到我的ViewModel。我认为可以单独设置DataContexts,但是如何让Buttons指向XAML中的ViewModel?
我找到了related post,但听起来并不像我想做的那样。我想在代码中创建ViewModel,而不是在XAML中创建。
答案 0 :(得分:1)
你的装订应该是这样的:
<Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TypeOfYourControlWithViewModelDataContext}}"/>