How to show tooltip in code in WPF

How to show tooltip in code? In the encoder below my question is better. Obviously, I don't want the code to check the position of the mouse, etc., Just how to display a tooltip.

private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
{
    // if mouse position equals certain coordinates show the tooltip
}
+4
source share
1 answer

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

Required Main conditionbecause the ToolTipcontrol can be installed in two ways:

First approach

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

This approach is most common. In this case, the contents of the tooltip will be an object, not a type ToolTip.

Second approach

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

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

Same:

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

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

ToolTip ToolTip. , ToolTip TestToolTip, .

, , ToolTip ToolTip :

toolTip.Content = control.ToolTip;

:

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

Source: https://habr.com/ru/post/1536316/


All Articles