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.
I rigged it, so that I handle the LeftMouseButtonDown
event in the code-behind and then display the context menu.
I'm using MVVM in my project which means I'm using DataTemplate
s 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?
Forget the "only xaml" thing. This can be solved nicely when you wrap it into attached behavior.
Here is a way to show context menu on left-click:
Create a new left button handler on the
Border
element:and then add this:
What it does, it basically maps the left-click into right-click. For reusability, you can wrap this into an attached behavior.
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.
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
I've just written and tested this based on HK1's answer (you can also read about attached properties in Attached Properties Overview) :
...
(note the comment inside the OnMouseLeftButtonUp() method)
While Caleb's answer is correct, it doesn't include working code. I setup an example using VB.NET (sorry) so I'm posting it here.
This answer does exactly the same job as the answer from @nightcoder (thanks for the inspiration!). It uses a Blend-style behavior which is a more modern approach compared to an attached property.
Then add the behavior to the button:
Elements such as an Ellipse or a Rectangle do not have an
OnClick
event, which means nothing really works very well for anything interactive. So wrap everything in a button to get thatOnClick
event. Might as well hint that the area is clickable by changing the mouse cursor to a hand on mouseover.