我有一个带有自定义菜单和一些按钮的窗口。当用户将鼠标放在菜单项上时,我使菜单自动展开。每个按钮都有“鼠标悬停”状态。我的问题是,当我将鼠标悬停在菜单上打开菜单后,按钮不再显示“鼠标悬停”状态。
这是我的窗口的简化版本:
<Window>
<Button Cursor="Hand" Width="20" Height="20">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="{TemplateBinding Background}" CornerRadius="30">
<Image Source="../Icons/close.png" Width="9" Height="9" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Gray" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<ScrollViewer>
<Menu ItemsSource="{Binding Path=CommandMenuItems}">
<Menu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Border>
<Grid>
<ContentPresenter />
<TextBlock />
<Grid />
<Popup IsOpen={Binding IsSubmenuOpen}"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True" />
<Condition Property="Role" Value="SubmenuHeader" />
</MultiTrigger.Conditions>
<Setter Property="IsSubmenuOpen" Value="True" />
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True" />
<Condition Property="Role" Value="TopLevelHeader" />
</MultiTrigger.Conditions>
<Setter Property="IsSubmenuOpen" Value="True" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Menu.ItemContainerStyle>
</ScrollViewer>
</Window>
我尝试在弹出窗口关闭时手动将焦点设置回窗口,但没有成功。
我终于找到答案了!事实证明,当光标离开弹出窗口时,菜单并没有释放鼠标。
向弹出窗口添加处理程序:
<Popup Closed="PART_Popup_Closed">
<!-- Popup contents here -->
</Popup>
并向处理程序添加:
private void PART_Popup_Closed(object sender, EventArgs e)
{
if(CommandMenu.IsMouseCaptured)
CommandMenu.ReleaseMouseCapture();
}
现在一切都很好。