WPF左键单击上下文菜单不会在第二次单击时消失

本文关键字:单击 第二次 消失 菜单 上下文 WPF | 更新日期: 2023-09-27 18:16:13

我已经为WPF按钮实现了一个新的行为,用于使用左键上下文菜单:

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>

它工作得很好,但我有一个小问题-在第二次点击按钮(在上下文菜单仍然打开期间),菜单关闭并立即重新打开,但预期的行为是关闭菜单- source.ContextMenu.IsOpen = !source.ContextMenu.IsOpen;。因此,似乎在MoseDown按钮被触发之前,其他一些功能关闭了菜单。如何避免这种情况?

WPF左键单击上下文菜单不会在第二次单击时消失

我想我已经找到解决办法了:

<Button Content="Left ContextMenu test" IsHitTestVisible="{Binding ElementName=cm, Path=IsOpen, Mode=OneWay, Converter={StaticResource BoolInverter}}">
    <i:Interaction.Behaviors>
        <extensions:LeftClickContextMenuButtonBehavior />
    </i:Interaction.Behaviors>
    <Button.ContextMenu>
        <ContextMenu x:Name="cm">
            <MenuItem Header="Item A" />
            <MenuItem Header="Item B" /> 
        </ContextMenu>
    </Button.ContextMenu>
</Button>

其中BoolInverterConverter定义为:

 public class BoolInverter : IValueConverter
 {
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
       if (value is bool)
         return !(bool)value;
       return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }

这样,当您第二次单击按钮时,没有单击,但上下文菜单将关闭,因为它失去了焦点。

试试这个:

void AssociatedObject_MouseDown(object sender, RoutedEventArgs e)
{
    e.handled = true;  // handle the event
    Button source = sender as Button;
    //rest of the code ...
}
祝你好运!