2

我正在尝试绑定一个按钮以在左键单击时打开其上下文菜单。我知道如何以编程方式执行此操作,但是有没有办法使用默认命令绑定来执行此操作?

我目前有:

    <Button Command="ApplicationCommands.ContextMenu">
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem ...

但没有这样的运气......如果我这样做,那么按钮就会被禁用。我猜这表明该命令无法执行,但为什么呢?

4

1 回答 1

7

你可以通过几种方式做到这一点,这里有两种:

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;
}
于 2013-06-24T18:32:27.283 回答