UserControl 的命令数据绑定问题 - 分离 DataContext?

发布于 2024-10-06 22:24:29 字数 970 浏览 0 评论 0原文

我之前发布的关于数据绑定和用户控件的问题中,我是在设置简单的属性以便我可以更改颜色、大小等时遇到问题。肯特给了我一些很好的指导,效果很好。然后我编写了一个新的用户控件,并根据他的建议,它也运行得很好。

现在我正在进行下一步——数据绑定命令。我当前的结构如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你怎么敢 2024-10-13 22:24:29

您的绑定应该如下所示:

<Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource     Mode=FindAncestor, AncestorType={x:Type TypeOfYourControlWithViewModelDataContext}}"/>

Your binding should look something like this:

<Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource     Mode=FindAncestor, AncestorType={x:Type TypeOfYourControlWithViewModelDataContext}}"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文