我有一个按钮,单击它会打开一个上下文菜单。我在同一个堆栈面板上有另一个按钮,当通过按钮2打开上下文菜单时,单击按钮1不会第一次触发按钮1的事件,但是当再次点击时,事件被触发。简单来说,当按钮2的上下文菜单打开时,我需要点击2次才能触发窗口上按钮1的事件。
以下是更多理解的代码:
MainWindow.xaml
<Grid MouseLeftButtonDown="Grid_MouseLeftButtonDown">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row = "0" Orientation="Horizontal">
<Button x:Name= "btnOne" Click="btnOneClick"/>
<Button x:Name="btnTwo"
RenderOptions.BitmapScalingMode="HighQuality" Cursor="Hand" ContextMenuService.IsEnabled="False" Click="btnTwoClick">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="MyContextMenu"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
<StackPanel>
<StackPanel Height="{Binding ActualHeight, ElementName=btnTwo}" Orientation="Horizontal" HorizontalAlignment="Right" >
<TextBlock HorizontalAlignment="Right" Text="Click Me" ></TextBlock>
</StackPanel>
</StackPanel>
<Button.ContextMenu>
<ContextMenu x:Name="MyContextMenu" StaysOpen="False" Width="200" MaxHeight="258"
BorderBrush="Gray" BorderThickness="1,0,1,1" Closed="MyContextMenuClosed">
<MenuItem Header="MenuOne" StaysOpenOnClick="True" Cursor="Arrow"/>
<MenuItem Header="MenuTwo" StaysOpenOnClick="True" Cursor="Arrow"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
</StackPanel>
</Grid>
MainWindow.xaml.cs
//When user clicks anywhere on the Grid
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//Close the Context menu if it's open
if (btnTwo.ContextMenu.IsOpen)
btnTwo.ContextMenu.IsOpen = false;
}
//When user clicks on btnTwo
private void btnTwoClick(object sender, RoutedEventArgs e)
{
if (!btnTwo.ContextMenu.IsOpen)
{
//Open the Context menu when Button is clicked
btnTwo.ContextMenu.IsEnabled = true;
btnTwo.ContextMenu.PlacementTarget = (sender as Button);
btnTwo.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
btnTwo.ContextMenu.IsOpen = true;
}
}
//When user clicks on btnOne, This event does does not fires when context menu is open
private void btnOneClick(object sender, RoutedEventArgs e)
{
}
答案 0 :(得分:1)
我无法解释,但是,如果你删除
StaysOpen="False"
在XAML中的ContextMenu
定义中,它将按预期的那样工作。顺便说一下 - 你不需要在XAML按钮的触发器和Click EventHandler中调用两次ContextMenu。
默认情况下,MSDN写入StaysOpen
为false。
如果菜单应保持打开,直到IsOpen属性更改为
假;否则,错误。默认值为false。