I've implemented a new behaviour for WPF button for using context menu with left click:
public class LeftClickContextMenuButtonBehavior : Behavior<Button>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.AddHandler(UIElement.MouseDownEvent, new RoutedEventHandler(AssociatedObject_MouseDown), true);
}
void AssociatedObject_MouseDown(object sender, RoutedEventArgs e)
{
Button source = sender as Button;
if (source != null && source.ContextMenu != null)
{
source.ContextMenu.PlacementTarget = source;
source.ContextMenu.Placement = PlacementMode.Bottom;
source.ContextMenu.IsOpen = !source.ContextMenu.IsOpen;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.RemoveHandler(UIElement.MouseDownEvent, new RoutedEventHandler(AssociatedObject_MouseDown));
}
}
XAML:
<Button Content="Left ContextMenu test">
<i:Interaction.Behaviors>
<extensions:LeftClickContextMenuButtonBehavior />
</i:Interaction.Behaviors>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Item A" />
<MenuItem Header="Item B" />
</ContextMenu>
</Button.ContextMenu>
</Button>
It works fine, but I have a small problem - on a second click on the button (during the context menu is still opened), menu closes and immediately re-opens, but expected behaviour is to close the menu - source.ContextMenu.IsOpen = !source.ContextMenu.IsOpen;. So it seems that before MoseDown on button is fired, some other fuctionality closes the menu. How to avoid that?