如何绑定到窗口的命令?

发布于 2024-12-14 05:25:36 字数 265 浏览 3 评论 0原文

我有一个名为“RefreshCommand”(ICommand 类型)的用户控件的依赖属性,我想将其绑定到主窗口中的命令。

如果我用代码编写它,它就可以工作......

MainToolbar.RefreshCommand = (ICommand)this.CommandBindings[0].Command;

但是我如何在 XAML 中表达它?

另外,我想通过名称而不是索引来引用该命令。

谢谢,

I have a dependency property on a user control called "RefreshCommand" (ICommand type) that I want to bind to a Command in my main window.

If I write this in code, it works...

MainToolbar.RefreshCommand = (ICommand)this.CommandBindings[0].Command;

.. but how can I express that in XAML?

I would additionally like to refer to the command by its name as opposed to its index.

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

红衣飘飘貌似仙 2024-12-21 05:25:36

在 XAML 中绑定到其他 XAML 元素

  • 您可以通过例如元素名称

RefreshCommand="{Binding ElementName=window, Path=CommandBindings[0].Command}"

  • On Properties of "yourself"

RefreshCommand="{BindingrelativeSource={x:StaticRelativeSource.Self}, Path=CommandBindings[0].Command}"

  • 沿着 AncestorType 树向上

RefreshCommand="{Binding Path=CommandBindings[0].Command,relativeSource={RelativeSource AncestorType={x:Type Window}}}"

如果工具栏是窗口的子工具栏,我想第三个应该工作顺利。

you can bind in XAML to other XAML Element through e.g.

  • The Element name:

RefreshCommand="{Binding ElementName=window, Path=CommandBindings[0].Command}"

  • On Properties of "yourself"

RefreshCommand="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=CommandBindings[0].Command}"

  • Upwards along the tree with AncestorType

RefreshCommand="{Binding Path=CommandBindings[0].Command, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

If the toolbar is a child from window, I suppose the third should work well.

樱花细雨 2024-12-21 05:25:36

我会建议这样做。

3 类

MainWindow.xaml (Window)
MainViewModel.cs (Class)
UserControl.xaml (UserControl)

将MainWindow 的数据上下文设置为ViewModel。 UserControl 将继承此数据上下文,除非您显式更改它。设置用户控件/主窗口上的控件以绑定到主视图模型上的中继命令。

这将为您提供所需的上下文,而无需对索引 (xxx.[0]) 进行硬编码,并且仍保持一定程度的分离。

I would recommend doing this then.

3 Classes

MainWindow.xaml (Window)
MainViewModel.cs (Class)
UserControl.xaml (UserControl)

Set the data context of the MainWindow to the ViewModel. The UserControl will inheret this data context unless you change it explicitly. Set up the controls on the user control / main window to bind to relay commands on the Main View Model.

This will give you the context you need without hard coding indexes (xxx.[0]) and still maintain a degree of separation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文