如何绑定到窗口的命令?
我有一个名为“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 XAML 中绑定到其他 XAML 元素
:
RefreshCommand="{Binding ElementName=window, Path=CommandBindings[0].Command}"
RefreshCommand="{BindingrelativeSource={x:StaticRelativeSource.Self}, Path=CommandBindings[0].Command}"
RefreshCommand="{Binding Path=CommandBindings[0].Command,relativeSource={RelativeSource AncestorType={x:Type Window}}}"
如果工具栏是窗口的子工具栏,我想第三个应该工作顺利。
you can bind in XAML to other XAML Element through e.g.
RefreshCommand="{Binding ElementName=window, Path=CommandBindings[0].Command}"
RefreshCommand="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=CommandBindings[0].Command}"
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.
我会建议这样做。
3 类
将MainWindow 的数据上下文设置为ViewModel。 UserControl 将继承此数据上下文,除非您显式更改它。设置用户控件/主窗口上的控件以绑定到主视图模型上的中继命令。
这将为您提供所需的上下文,而无需对索引 (xxx.[0]) 进行硬编码,并且仍保持一定程度的分离。
I would recommend doing this then.
3 Classes
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.