开发者

Silverlight: Showing popup whenever mouse is over the owner element or over the popup itself

开发者 https://www.devze.com 2023-03-16 22:51 出处:网络
I\'m trying to build a popup that shows up when the user has the mouse over an element. If the user moves the mouse over the popup, I want it to stay displayed. However, if the user leaves both the ow

I'm trying to build a popup that shows up when the user has the mouse over an element. If the user moves the mouse over the popup, I want it to stay displayed. However, if the user leaves both the owner element and the popup element, then the popup element should disappear.

I tried the following but it does not work:

<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>

Code behind:

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;
    }
}

What happens is the MouseLeave of the owner element (Root) is triggered and the Popup gets hidden.

Any ideas ?


Use a DispatcherTimer to actually set IsOpen to false like this:-

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();
    }
}

also move the MouseEnter MouseMove events off the Popup and onto the StackPanel inside the popup.

0

精彩评论

暂无评论...
验证码 换一张
取 消