Skip to content

Instantly share code, notes, and snippets.

@eman41
Last active August 29, 2015 14:20
Show Gist options
  • Save eman41/14078e405433828423b5 to your computer and use it in GitHub Desktop.
Save eman41/14078e405433828423b5 to your computer and use it in GitHub Desktop.
This is an attached behavior that will show the `ContextMenu` for a Button control when left-clicked.
// LeftClickContextMenuBehavior.cs, 4/30/2015 5:49:44 PM
using System;
using System.Windows;
using System.Windows.Controls;
namespace Common.AttachedBehaviors
{
public static class LeftClickContextMenuBehavior
{
private static readonly DependencyProperty LeftClickContextMenuProperty = DependencyProperty.RegisterAttached(
"Enabled", typeof(bool), typeof(LeftClickContextMenuBehavior), new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged))
);
public static bool GetEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(LeftClickContextMenuProperty);
}
public static void SetEnabled(DependencyObject obj, bool value)
{
obj.SetValue(LeftClickContextMenuProperty, value);
}
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if(d is Button)
{
var button = (Button)d;
button.Click -= OnMouseClick;
button.Click += OnMouseClick;
}
}
private static void OnMouseClick(object sender, RoutedEventArgs e)
{
var obj = sender as DependencyObject;
bool enabled = (bool)obj.GetValue(LeftClickContextMenuProperty);
if (!enabled)
return;
Button b = sender as Button;
if (HasContextMenu(b))
{
b.ContextMenu.PlacementTarget = b;
b.ContextMenu.IsOpen = true;
}
}
private static bool HasContextMenu(Button b)
{
return b != null && b.ContextMenu != null;
}
}
}
@eman41
Copy link
Author

eman41 commented Apr 30, 2015

Usage:

<!-- controls is the namespace containing the behavior -->
<Button Style="{StaticResource ButtonStyle}" controls:LeftClickContextMenuBehavior.Enabled="True"/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment