WPF Context menu on left click

后端 未结 8 511
情深已故
情深已故 2020-12-01 10:39

I have a WPF application..In which I have an Image control in Xaml file.

On right click of this image I have a context menu.

I would like to have same to be

8条回答
  •  一生所求
    2020-12-01 11:00

    You can invent your own DependencyProperty which opens a context menu when image is clicked, just like this:

      
          ...
          
      
    

    And here is a C# code for that property:

    public class ClickOpensContextMenuBehavior
    {
      private static readonly DependencyProperty ClickOpensContextMenuProperty =
        DependencyProperty.RegisterAttached(
          "Enabled", typeof(bool), typeof(ClickOpensContextMenuBehavior),
          new PropertyMetadata(new PropertyChangedCallback(HandlePropertyChanged))
        );
    
      public static bool GetEnabled(DependencyObject obj)
      {
        return (bool)obj.GetValue(ClickOpensContextMenuProperty);
      }
    
      public static void SetEnabled(DependencyObject obj, bool value)
      {
        obj.SetValue(ClickOpensContextMenuProperty, value);
      }
    
      private static void HandlePropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs args)
      {
        if (obj is Image) {
          var image = obj as Image;
          image.MouseLeftButtonDown -= ExecuteMouseDown;
          image.MouseLeftButtonDown += ExecuteMouseDown;
        }
    
        if (obj is Hyperlink) {
          var hyperlink = obj as Hyperlink;
          hyperlink.Click -= ExecuteClick;
          hyperlink.Click += ExecuteClick;
        }
      }
    
      private static void ExecuteMouseDown(object sender, MouseEventArgs args)
      {
        DependencyObject obj = sender as DependencyObject;
        bool enabled = (bool)obj.GetValue(ClickOpensContextMenuProperty);
        if (enabled) {
          if (sender is Image) {
            var image = (Image)sender;
            if (image.ContextMenu != null)
              image.ContextMenu.IsOpen = true;
          }
        }
      } 
    
      private static void ExecuteClick(object sender, RoutedEventArgs args)
      {
        DependencyObject obj = sender as DependencyObject;
        bool enabled = (bool)obj.GetValue(ClickOpensContextMenuProperty);
        if (enabled) {
          if (sender is Hyperlink) {
            var hyperlink = (Hyperlink)sender;
            if(hyperlink.ContextMenu != null)
              hyperlink.ContextMenu.IsOpen = true;
          }
        }
      } 
    }
    

提交回复
热议问题