WPF 左键单击上下文菜单
我有一个 WPF 应用程序..其中我在 Xaml 文件中有一个图像控件。
右键单击该图像,我有一个上下文菜单。
我希望在“左键单击”上也显示相同的内容。
我如何以 MVVM 方式做到这一点?
I have a WPF application..In which I have an Image control in Xaml file.
On right click of this image I have a context menu.
I would like to have same to be displayed on "Left click" also.
How do I do this in MVVM way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这是仅 XAML 的解决方案。
只需将此样式添加到您的按钮即可。
这将导致上下文菜单在左键单击和右键单击时打开。享受!
Here is a XAML only solution.
Just add this style to your button.
This will cause the context menu to open on both left and right click. Enjoy!
您可以通过使用像这样的图像的 MouseDown 事件来完成此操作
,然后在后面的代码中的 EventHandler 中显示 ContextMenu
You can do this by using the MouseDown event of an Image like this
And then show the ContextMenu in the EventHandler in code behind
您可以发明自己的 DependencyProperty,它会在单击图像时打开上下文菜单,如下所示:
下面是该属性的 C# 代码:
You can invent your own DependencyProperty which opens a context menu when image is clicked, just like this:
And here is a C# code for that property:
如果您只想在 Xaml 中执行此操作而不使用代码隐藏,则可以使用 Expression Blend 的触发器支持:
If you want to do this just in Xaml without using code-behind you can use Expression Blend's triggers support:
您只需将代码添加到函数 Image_MouseDown
e.Handled = true;
那么它就不会消失。
you only need add the code into function Image_MouseDown
e.Handled = true;
Then it will not disappear.
交互性已经过时,不再支持。新的实施方法是:
Interactivity is old and not support any more. The new approach for the implementation is:
嘿,我遇到了同样的问题,正在寻找解决方案,但我在这里找不到。
我对 MVVM 一无所知,所以它可能不符合 MVVM,但它对我有用。
第 1 步:为上下文菜单命名。
步骤2:双击控制对象并插入此代码。顺序很重要!
第 3 步:享受
这将对左和右做出反应。右键单击。它是一个带有 ImageBrush 和 ControlTemplate 的按钮。
Hey I came across the same problem looking for a solution which I didn't find here.
I don't know anything about MVVM so it's probably not MVVM conform but it worked for me.
Step 1: Give your context menu a name.
Step 2: Double click the control object and insert this code. Order matters!
Step 3: Enjoy
This will react for left & right click. It's a button with a ImageBrush with a ControlTemplate.
您可以将 contextMenu 的 Isopen 属性绑定到 viewModel 中的属性,例如“IsContextMenuOpen”。
但问题是您无法将上下文菜单直接绑定到 viewModel,因为它不是 userControl 层次结构的一部分。因此,要解决此问题,您应该将 tag 属性绑定到视图的 dataontext。
祝你好运。
you can bind the Isopen Property of the contextMenu to a property in your viewModel like "IsContextMenuOpen".
but the problem is your can't bind directly the contextmenu to your viewModel because it's not a part of your userControl hiarchy.So to resolve this you should bing the tag property to the dataontext of your view.
Good luck.
XAML
C#
XAML
C#