dissaepear我實現了WPF按鈕,一個新的行爲使用上下文菜單左鍵點擊: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 on按鈕被觸發之前,其他一些功能會關閉菜單。如何避免這種情況?
我不認爲這會奏效。問題與未處理的事件無關。 – Giangregorio