How to show tooltip in code behind in WPF

2019-02-23 12:39发布

问题:

How can I show a tooltip in code-behind? The code below defines my question better. Obviously I don't want the code to check for mouse position etc, just how to display the tooltip.

private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
{
    // if mouse position equals certain coordinates show the tooltip
}

回答1:

Try like this:

if (control.ToolTip != null)
{
    // Main condition
    if (control.ToolTip is ToolTip)
    {
        var castToolTip = (ToolTip)control.ToolTip;
        castToolTip.IsOpen = true;
    }
    else
    {
        toolTip.Content = control.ToolTip;
        toolTip.StaysOpen = false;
        toolTip.IsOpen = true;
    }
}  

The Main condition necessary, because ToolTip for Control can be set in two approaches:

First approach

<Button Name="TestButton"
        ToolTip="TestToolTip" />

This approach is most common. In this case, the content of the ToolTip will object and not type of ToolTip.

Second approach

<Button Name="TestButton"
        Content="Test">

    <Button.ToolTip>
        <ToolTip>TestToolTip</ToolTip>
    </Button.ToolTip>
</Button>

Is the same as this:

<Button Name="TestButton"
        Content="Test">

    <Button.ToolTip>
        TestToolTip
    </Button.ToolTip>
</Button> 

In this case, the Content type of ToolTip will be Tooltip. Note that in the second case, the object automatically fills ToolTip object on line TestToolTip, hence this approach will work a bit slower.

Therefore, this check is needed to avoid an exception when we try to assign to the ToolTip the content of the ToolTip type here:

toolTip.Content = control.ToolTip;

Below is a full example:

XAML

<Grid>
    <Button Name="TestButton"
            Width="100"
            Height="25"
            Content="Test" 
            ToolTip="TestToolTip" />

    <Button Name="ShowToolTip" 
            VerticalAlignment="Top"
            Content="ShowToolTip" 
            Click="ShowToolTip_Click" />
</Grid>

Code-behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ShowToolTip_Click(object sender, RoutedEventArgs e)
    {
        var toolTip = new ToolTip();

        if (TestButton.ToolTip != null)
        {
            if (TestButton.ToolTip is ToolTip)
            {
                var castToolTip = (ToolTip)TestButton.ToolTip;
                castToolTip.IsOpen = true;
            }
            else
            {
                toolTip.Content = TestButton.ToolTip;
                toolTip.StaysOpen = false;
                toolTip.IsOpen = true;
            }
        }  
    }
}


标签: c# wpf tooltip