WPF:绑定到命令的 ContextMenu 项仅在从另一个源调用该命令后才启用。为什么会这样呢?

发布于 2024-08-25 03:42:58 字数 166 浏览 4 评论 0原文

我有一个 ContextMenu,其项目全部绑定到命令,并在从另一个源调用任何命令之后正确启用/禁用,但在此之前,它们全部被禁用。因此,如果我运行该应用程序,所有菜单项都会被禁用,但如果我从另一个源(例如按钮)调用任何绑定命令,它们就会与 CanExecute 代码同步。我不知道如何调试这个。任何想法都会有帮助!?!

I have a ContextMenu whose items are all bound to commands and enable/disable correctly after ANY Command is invoked from another source but prior to, they are all disabled. So if I run the app, all the MenuItems are disabled but if I invoke any of the bound commands from another source (buttons, for instance) they become synchronized with the CanExecute code. I have no idea how to debug this. Any thought would be helpful!?!

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

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

发布评论

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

评论(2

川水往事 2024-09-01 03:42:58

似乎是一个错误,窗口的主焦点范围内没有焦点元素。
解决方法是将 MenuItem 的 CommandTarget 绑定到主窗口。

Marco Zhou 的回答在这里:
http://social.msdn .microsoft.com/Forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455

<Window.ContextMenu>
    <ContextMenu >
      <ContextMenu.Items>
        <MenuItem Command="ApplicationCommands.Open" 
                  CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/> 
      </ContextMenu.Items>
    </ContextMenu>
  </Window.ContextMenu>

Seems to be a bug where there is no focused element in the window's main focus scope.
A workaround is to bind MenuItem's CommandTarget to the main window.

Answer from Marco Zhou here:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455

<Window.ContextMenu>
    <ContextMenu >
      <ContextMenu.Items>
        <MenuItem Command="ApplicationCommands.Open" 
                  CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/> 
      </ContextMenu.Items>
    </ContextMenu>
  </Window.ContextMenu>
℉絮湮 2024-09-01 03:42:58

有时您需要强制 WPF 重新评估命令是否启用。

在代码中的某个位置添加对以下内容的调用:

CommandManager.InvalidateRequerySuggested();

看看是否有帮助。

Sometimes you need to force WPF to re-evaluate whether commands are enabled or not.

Somewhere in your code, add a call to:

CommandManager.InvalidateRequerySuggested();

See if that helps.

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