WPF根据对象属性隐藏ContextMenu上的MenuItem
我需要以编程方式显示/隐藏菜单项,最好的方法是什么?
I need to programatically show/hide a MenuItem, what would be the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,要添加一个 MenuItem,您将需要以下内容:(
但您可能已经有了这个)。
您将需要某种方法将菜单项绑定到属性 - 但如果没有看到您的应用程序,我无法真正建议最好的方法。 Tag 属性存储一个对象; 存储字符串的 Uid 属性; Name 属性也存储一个字符串。
While:
并且
应该切换项目的可见性。
编辑:使用折叠将隐藏菜单项,并且不会在菜单中保留空间 - 您实际上并不希望上下文菜单中存在空白。 (感谢 Botz3000)
然后,在更改属性值的代码中,您将使用我上面描述的链接找到您希望显示/隐藏的菜单项。 获得该物品后,您可以更改其价值:
Well, to add a MenuItem you'll need something along these lines:
(but you've probably already got this).
You will need some way of tying the menu item to the property - but without seeing your application I can't really suggest the best way. There's the Tag property which stores an object; the Uid property which stores a string; the Name property which also stores a string.
While:
and
should toggle the visibility of the item.
EDIT: Using Collapsed will hide the menu item and not reserve space in the menu - you don't really want blank spaces in a context menu. (thanks to Botz3000 for this)
Then in your code where the property value is changed you'll to find the menu item you wish to show/hide using the linkage I described above. Once you have the item you can switch it's value:
您确定要隐藏
MenuItem
吗? 更常见的是使用 WPF 的命令框架禁用它:WPF 将使用
Save_CanExecute
的bool
结果来确定MenuItem
的命令是否有效当前可以执行,并相应地启用/禁用MenuItem
。Are you sure you want to hide the
MenuItem
? It is more common to disable it, using WPF's commanding framework:WPF will use the
bool
result ofSave_CanExecute
to determine whether theMenuItem
's command can currently execute, and enable/disable theMenuItem
accordingly.