【问题标题】:commandbinding not working?命令绑定不起作用?
【发布时间】:2011-05-20 10:18:14
【问题描述】:

我正在开发一个多选项卡应用程序(例如:多选项卡文本编辑器),其中每个 tabitem 都有自己的内容。在 tabitem 的 contextmenu 中,它们是带有命令的 menuitem,比如 SelectAll 命令。

运行应用程序后,菜单项始终处于禁用状态,不执行任何命令。

那么,我怎样才能使我的命令绑定工作?

代码::

在 TextEditor 的上下文菜单中>

<MenuItem Command="local:TextEditor.SelectAllCommand" Header="Select All" />

在 TextEditor 的 CommandBindings 中>

<UserControl.CommandBindings>
  <CommandBinding Command="local:TextEditor.SelectAllCommand" 
                  Executed="SelectAll_Executed" CanExecute="SelectAll_CanExecute" />
</UserControl.CommandBindings>

带有 TextEditor 的 TabItem 是在运行时创建的

【问题讨论】:

  • 第一步可能是与我们分享代码
  • @Snowbear JIM-compiler 如果在这里发布代码会很乱。

标签: wpf command


【解决方案1】:

这是因为 ContextMenus 是具有自己的 VisualTree 和 LogicalTree 的独立窗口。

这样使用

<MenuItem Header="Cut" Command="Cut" CommandTarget="
          {Binding Path=PlacementTarget, 
          RelativeSource={RelativeSource FindAncestor, 
          AncestorType={x:Type ContextMenu}}}"/>

更多内容请点击下方链接

http://www.wpftutorial.net/RoutedCommandsInContextMenu.html

【讨论】:

  • 感谢此链接和您的帮助
  • 这很好用。但 XAML 编辑器显示虚假的“对象引用未设置为对象的实例”。一旦编译并运行它就可以正常工作,但最好不要在编辑器中显示错误。有什么办法解决吗?
【解决方案2】:

查看 biju 答案,您的 ContextMenu 的 DataContext 不是您所期望的。

如果您以后有任何绑定问题,请查看Snoop。它是一个易于使用的工具,可在运行时检查您的绑定。

我总是检查两件事:

  • 我的 DataContext 是我期望的吗?!
  • 是我想要的绑定路径吗?!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多