Skip to content

Instantly share code, notes, and snippets.

@jammerxd
Created December 1, 2015 22:59
Show Gist options
  • Save jammerxd/3ad2477a29648522a675 to your computer and use it in GitHub Desktop.
Save jammerxd/3ad2477a29648522a675 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
namespace Twitch_Desktop_Manager.Resources.Helpers
{
public static class ContextMenuLeftClickBehavior
{
public static bool GetIsLeftClickEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsLeftClickEnabledProperty);
}
public static void SetIsLeftClickEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsLeftClickEnabledProperty, value);
}
public static readonly DependencyProperty IsLeftClickEnabledProperty = DependencyProperty.RegisterAttached(
"IsLeftClickEnabled",
typeof(bool),
typeof(ContextMenuLeftClickBehavior),
new UIPropertyMetadata(false, OnIsLeftClickEnabledChanged));
private static void OnIsLeftClickEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var uiElement = sender as UIElement;
if (uiElement != null)
{
bool IsEnabled = e.NewValue is bool && (bool)e.NewValue;
if (IsEnabled)
{
if (uiElement is ButtonBase)
((ButtonBase)uiElement).Click += OnMouseLeftButtonUp;
else
uiElement.MouseLeftButtonUp += OnMouseLeftButtonUp;
}
else
{
if (uiElement is ButtonBase)
((ButtonBase)uiElement).Click -= OnMouseLeftButtonUp;
else
uiElement.MouseLeftButtonUp -= OnMouseLeftButtonUp;
}
}
}
private static void OnMouseLeftButtonUp(object sender, RoutedEventArgs e)
{
var fe = sender as FrameworkElement;
if (fe != null)
{
// if we use binding in our context menu, then it's DataContext won't be set when we show the menu on left click
// (it seems setting DataContext for ContextMenu is hardcoded in WPF when user right clicks on a control, although I'm not sure)
// so we have to set up ContextMenu.DataContext manually here
if (fe.ContextMenu.DataContext == null)
{
fe.ContextMenu.SetBinding(FrameworkElement.DataContextProperty, new Binding { Source = fe.DataContext });
}
fe.ContextMenu.IsOpen = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment