我尝试打开ContextMenu上的按钮,单击左键而不是单击右键,所以我做了如下操作。但是菜单项“全部”和“选定的”不会在.cs中触发它们各自的事件。
Xaml
<Button Content="Import" ContextMenuService.IsEnabled="false">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="All"
Click="ImportAll_Click"/>
<MenuItem Header="Selected"
Click="ImportSelected_Click"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
Xaml.cs
private void ImportAll_Click(object sender, RoutedEventArgs e)
{
}
private void ImportSelected_Click(object sender, RoutedEventArgs e)
{
}
我这里缺少什么吗?
答案 0 :(得分:2)
尝试将ContextMenu
定义为资源:
<Button Content="Import" ContextMenuService.IsEnabled="false">
<Button.Resources>
<ContextMenu x:Key="cm">
<MenuItem Header="All" Click="ImportAll_Click"/>
<MenuItem Header="Selected" Click="ImportSelected_Click"/>
</ContextMenu>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu" Value="{StaticResource cm}" />
</Style>
</Button.Style>
</Button>