WPF左键单击ContextMenu在第二次单击时不会出现异常情况

时间:2015-10-05 08:41:52

标签: c# .net wpf xaml

我已经为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>

它工作正常,但我有一个小问题 - 再次点击按钮(在上下文菜单中仍然打开),菜单关闭并立即重新打开,但预期的行为是关闭菜单 - {{ 1}}。因此,似乎在MoseDown on按钮被触发之前,其他一些功能会关闭菜单。如何避免?

2 个答案:

答案 0 :(得分:1)

I think i've found a solution:

<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>

Where the BoolInverterConverter is defined as:

 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();
    }
  }

In this way when you click the button for the second time is not clicked but the context menu will close because it lost focus.

答案 1 :(得分:0)

试试这个:

void AssociatedObject_MouseDown(object sender, RoutedEventArgs e)
{
    e.handled = true;  // handle the event
    Button source = sender as Button;

    //rest of the code ...
}

祝你好运!