我正在尝试构建一个弹出窗口,当用户将鼠标悬停在元素上时会显示该弹出窗口。如果用户将鼠标移到弹出窗口上,我希望它保持显示状态。但是,如果用户同时保留owner元素和popup元素,则弹出元素应该消失。
我尝试了以下但不起作用:
<UserControl x:Class="SilverlightApplication1.MainPage"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<StackPanel MouseEnter="OnMouseEnter" MouseMove="OnMouseMove" MouseLeave="OnMouseLeave">
<HyperlinkButton Content="Root" HorizontalAlignment="Left"/>
<Popup x:Name="popup" MouseEnter="OnMouseEnter" MouseMove="OnMouseMove" MouseLeave="OnMouseLeave">
<StackPanel x:Name="leaves" HorizontalAlignment="Left">
<HyperlinkButton Content="Leaf1" />
<HyperlinkButton Content="Leaf2" />
</StackPanel>
</Popup>
</StackPanel>
代码背后:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
this.popup.IsOpen = true;
}
private void OnMouseEnter(object sender, MouseEventArgs e)
{
this.popup.IsOpen = true;
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
this.popup.IsOpen = false;
}
}
触发所有者元素(Root)的MouseLeave并弹出Popup会发生什么。
有什么想法吗?
答案 0 :(得分:2)
使用DispatcherTimer将IsOpen
实际设置为false,如下所示: -
public partial class MainPage: UserControl
{
DispatcherTimer popupTimer = new DispatcherTimer();
public MainPage()
{
InitializeComponent();
popupTimer.Interval = TimeSpan.FromMilliseconds(100);
popupTimer.Tick += new EventHandler(popupTimer_Tick);
}
void popupTimer_Tick(object sender, EventArgs e)
{
popupTimer.Stop();
popup.IsOpen = false;
}
private void OnMouseEnter(object sender, MouseEventArgs e)
{
popupTimer.Stop();
popup.IsOpen = true;
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
popupTimer.Start();
}
}
还将MouseEnter MouseMove事件从Popup
移到弹出窗口内的StackPanel
。