Search code examples
silverlightxamltooltipsilverlight-5.0

Dynamic Tooltip in Silverlight


I have a tooltip that I have to set through code like that :

private ToolTip _tooltip;
private void btnTest_MouseEnter(object sender, MouseEventArgs e)
{

    if (_tooltip == null)
    {
        _tooltip = CreateToolTip();
        ToolTipService.SetToolTip(btnTest, _tooltip);

        _tooltip.IsOpen = true;
    }

}

private void btnTest_MouseLeave(object sender, MouseEventArgs e)
{
    if (_tooltip != null)
        _tooltip.IsOpen = false;
}

The first time it enters the btnTest, the tooltip gets create and is associated to btnTest. Then we need to set IsOpen = true to show the tooltip immediately.

When the mouse leaves the button it sets IsOpen = false.

This is working fine, but my btnTest is likely to disapear at anytime, so if we set its Visibility = Collapsed while the "first" tooltip is opened, the tooltip will remain opened (the MouseLeave will never be called)


Solution

  • Use the Unloaded event. It will be fired no matter whether the button is removed from the view or just set to Collapsed.

    private ToolTip _tooltip;
    private void btnTest_MouseEnter(object sender, MouseEventArgs e)
    {
    
        if (_tooltip == null)
        {
            _tooltip = CreateToolTip();
            ToolTipService.SetToolTip(btnTest, _tooltip);
            btnTest.Unloaded += CloseAndDetachTooltip;
        }
        _tooltip.IsOpen = true;
    }
    
    private void CloseAndDetachTooltip(object sender, EventArgs args)
    {
        TryCloseTooltip();
        ToolTipService.SetToolTip(btnTest, null);
        _tooltip = null;
    }
    
    private void TryCloseTooltip()
    {
        if (_tooltip != null) _tooltip.IsOpen = false;
    }
    
    private void btnTest_MouseLeave(object sender, MouseEventArgs e)
    {
        TryCloseTooltip();
    }