UserControl 的命令数据绑定问题 - 分离 DataContext?
在我之前发布的关于数据绑定和用户控件的问题中,我是在设置简单的属性以便我可以更改颜色、大小等时遇到问题。肯特给了我一些很好的指导,效果很好。然后我编写了一个新的用户控件,并根据他的建议,它也运行得很好。
现在我正在进行下一步——数据绑定命令。我当前的结构如下所示:
Window --contains--> UserControlB --包含--> UserControlA
现在,UserControlA 中的数据绑定属性工作得很好,并且我的 UserControlB 公开了这些相同的属性,以便窗口可以间接更改 UserControlA。问题是 UserControlB 的 DataContext 设置如下:
<UserControl x:Name="root">
<Grid DataContext="{Binding ElementName=root}">
...
<Button Command="{Binding MyCommand}" />
...
</Grid>
</UserControl>
但我希望 MyCommand 绑定到我的 ViewModel。我认为可以单独设置 DataContext,但是如何让 Button 指向 XAML 中的 ViewModel?
我找到了相关帖子,但没有听起来像是我想做的。我想在代码中而不是在 XAML 中创建 ViewModel。
In a question I had posted before regarding databinding and UserControls, I was having problems getting simple properties set so that I could change colors, size, etc. Kent gave me some great pointers and that worked great. I then authored a new UserControl, and using his advice, had that working great as well.
Now I'm at the next step -- databinding commands. My current structure looks like this:
Window --contains--> UserControlB --contains--> UserControlA
Now databinding properties in UserControlA work great, and my UserControlB exposes these same properties so that the Window can change UserControlA indirectly. The problem is that UserControlB's DataContext is set something like this:
<UserControl x:Name="root">
<Grid DataContext="{Binding ElementName=root}">
...
<Button Command="{Binding MyCommand}" />
...
</Grid>
</UserControl>
But I want MyCommand to be bound to my ViewModel. I thought it wass possible to set the DataContexts separately, but how do I get the Buttons to point to my ViewModel in XAML?
I found a related post, but didn't sound like what I want to do. I want to create the ViewModel in code, not in XAML.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的绑定应该如下所示:
Your binding should look something like this: