仅使用XAML在左键单击上显示ContextMenu [英] Show ContextMenu on Left Click using only XAML

查看:64
本文介绍了仅使用XAML在左键单击上显示ContextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WPF ContextMenu 的默认行为是在用户右键单击时显示它。我希望 ContextMenu 在用户左键单击时显示。看来这应该是 ContextMenu 上的简单属性,但事实并非如此。

The default behavior of a WPF ContextMenu is to display it when the user right-clicks. I want the ContextMenu to show when the user left-clicks. It seems like this should be a simple property on ContextMenu, but it is not.

我操纵了它,所以我在代码后面处理 LeftMouseButtonDown 事件,然后显示上下文菜单。

I rigged it, so that I handle the LeftMouseButtonDown event in the code-behind and then display the context menu.

我在项目中使用MVVM,这意味着我将 DataTemplate s用于具有上下文菜单。摆脱掉后面的代码,找到一种使用XAML中的触发器或属性显示上下文菜单的方法,这会更加优雅。

I'm using MVVM in my project which means I'm using DataTemplates for the items that have the context menus. It would be much more elegant to get rid of the code-behind and find a way to display the context menu using triggers or properties in the XAML.

对此问题有任何想法或解决方案吗?

Any ideas or solutions to this issue?

推荐答案

我做什么建议做一个带有附加的DependencyProperty的新静态类。调用类LeftClickContextMenu和属性Enabled(仅是想法)。当您注册DependencyProperty时,添加一个on更改的回调。然后在属性更改的回调中,如果Enabled设置为true,则向LeftMouseButtonDown事件添加一个处理程序,然后在其中进行处理。如果Enabled设置为false,则删除处理程序。通过使用xaml中的以下命令,可以使您将它设置为任何属性的属性。

What I would suggest doing is making a new static class with attached DependencyProperty. Call the class LeftClickContextMenu and the property Enabled (just ideas). When your registering the DependencyProperty add an on changed callback. Then in the property changed callback if Enabled is set to true then add a handler to the LeftMouseButtonDown event and do your stuff there. If Enabled is set to false remove the handler. This sould allow you to set it like a property on anything by simply using the following in your xaml.

<Border namespace:LeftClickContextMenu.Enabled="True" />

此技术称为附加行为,您可以在此代码项目文章中了解有关此内容的更多信息:< a href = http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx rel = noreferrer> http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

This technique is called an attached behavior and you can read more about it in this code project article: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

这篇关于仅使用XAML在左键单击上显示ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆