我正在尝试绑定按钮以在左键单击时打开其上下文菜单。我知道如何以编程方式执行此操作,但有没有办法使用默认命令绑定?
我现在有:
<Button Command="ApplicationCommands.ContextMenu">
<Button.ContextMenu>
<ContextMenu>
<MenuItem ...
但没有这样的运气......如果我这样做,那么按钮被禁用。我想这表明命令无法执行,但为什么?
答案 0 :(得分:6)
你可以用几种方式做到这一点,其中有两个:
1)纯XAML
<Button Content="My Button">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
<Button.ContextMenu>
<ContextMenu >
<MenuItem Header="ABC"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
2)使用活动
<Button Content="My Button" Click="Button_Click">
<Button.ContextMenu>
<ContextMenu >
<MenuItem Header="ABC"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
private void Button_Click(object sender, RoutedEventArgs e)
{
ContextMenu contextMenu = (sender as Button).ContextMenu;
contextMenu.PlacementTarget = sender as UIElement;
contextMenu.IsOpen = true;
}