我正在使用以下代码在 WPF 中测试弹出窗口控件
<Window x:Class="Popup1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Popup1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="250">
<Grid>
<TextBlock TextWrapping="Wrap">You can use a popup to provide a link for a specific
<Run TextDecorations="Underline" MouseEnter="ContentElement_OnMouseEnter">
term
</Run>
</TextBlock>
<Popup Name="popLink" StaysOpen="False" Placement="Mouse" MaxWidth="200"
PopupAnimation="Slide" AllowsTransparency="True">
<Border>
<TextBlock Margin="10" TextWrapping="Wrap">
For more information, see
<Hyperlink NavigateUri="http://en.wikipedia.org/wiki/Term" Click="Hyperlink_OnClick">Wikipedia</Hyperlink>
</TextBlock>
</Border>
</Popup>
</Grid>
</Window>
和处理程序
private void ContentElement_OnMouseEnter(object sender, MouseEventArgs e) {
popLink.IsOpen = true;
}
private void Hyperlink_OnClick(object sender, RoutedEventArgs e) {
Process.Start(((Hyperlink) sender).NavigateUri.ToString());
}
结果是一个简单的窗口,其中包含一个textblock
,其中包含指向弹出窗口控件的链接,当鼠标悬停在弹出窗口的链接上时,该弹出窗口控件以可视方式显示。正常行为是弹出窗口在鼠标单击之前保持可见。只要鼠标单击不在弹出窗口的链接上,就可以正常工作
当我在弹出窗口的链接上单击鼠标时,我无法解释的奇怪行为就会发生。然后,弹出窗口关闭(按预期(,但当鼠标悬停在链接上时,它永远不会再次出现(它应该(。
你能解释一下这种行为吗?
如前所述,原因可能是关闭弹出窗口和重新打开之间的竞争条件,因为鼠标位于文本块上。您可以通过延迟弹出窗口打开操作直到当前工作完成来防止这种情况:
private void ContentElement_OnMouseEnter(object sender, MouseEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() => popLink.IsOpen = true));
}
关于标题文本:MouseEnter 事件实际上已触发(调试它!(,只是其中的操作没有按预期工作,因为弹出窗口处于不一致的状态。
经过一些调整后,如果我们为 Popup Close 事件添加一个额外的事件(与初始代码相比(处理程序,该处理程序在弹出窗口关闭时将 IsOpen 属性设置为 false
private void PopLink_OnClosed(object sender, EventArgs e) {
if (popLink.IsOpen) {
popLink.IsOpen = false;
}
}
和 XAML 中的改进
<Popup Name="popLink" StaysOpen="False" Placement="Mouse" MaxWidth="200"
PopupAnimation="Slide" AllowsTransparency="True"
Closed="PopLink_OnClosed">
<Border Background="Bisque">
<TextBlock Margin="10" TextWrapping="Wrap">
For more information, see
<Hyperlink NavigateUri="http://en.wikipedia.org/wiki/Term" Click="Hyperlink_OnClick">Wikipedia</Hyperlink>
</TextBlock>
</Border>
</Popup>