WPF Tooltip positioning

前端 未结 1 1378
旧时难觅i
旧时难觅i 2021-01-05 05:34

I have a style on my WPF Tooltip which basically makes it look like a speech bubble. The pointy part of the bubble stops aligning properly when the control is to the right o

1条回答
  •  一个人的身影
    2021-01-05 06:05

    Standard WPF Windows 7 style

    Standard WPF Windows 7 style

    The standard WPF tooltip positions at the mouse pointer, which look perfect in my opinion.

    The picture below illustrates your problem

    Styled ToolTip with no code-behind

    If you really want to do what you are asking, it is possible: you need code-behind on the style to calculate the horizontal adjustment, put this into ToolTip.Tag, and bind the pointy part border to the calculated adjustment:

    Revised ToolTip style -

        
    

    Code-behind

    private void ToolTipOpenedHandler(object sender, RoutedEventArgs e)
    {
        ToolTip toolTip = (ToolTip) sender;
        UIElement target = toolTip.PlacementTarget;
        Point adjust = target.TranslatePoint(new Point(8, 0), toolTip);
        toolTip.Tag = new Thickness(adjust.X, 0, 0, -1.5);
    }
    

    This answers your question as asked,

    Styled ToolTip - Top Right

    but is not sufficient when tooltip is near the bottom of the screen:

    Styled ToolTip - Bottom Right

    To fix this you can amend the code-behind to detect that the tooltip is above the target and set the tooltip Position to Top, and a Property Trigger style the tooltip with the pointy part below the rectangle -

    Complete XAML (includes wide, narrow and multi-line tooptips)

    
        
            
        
        
            TopLeft
            TopRight
            CenterLeft
            CenterRight
            
                
                    Multi-line ToolTip for Bottomleft - MMMMMMMMMWWWWWWWWWWxyz
                
            
            BottomRight
        
    
    

    Code-behind

    private void ToolTipOpenedHandler(object sender, RoutedEventArgs e)
    {
        ToolTip toolTip = (ToolTip)sender;
        UIElement target = toolTip.PlacementTarget;
        Point adjust = target.TranslatePoint(new Point(8, 0), toolTip);
        if (adjust.Y > 0)
        {
            toolTip.Placement = PlacementMode.Top;
        }
        toolTip.Tag = new Thickness(adjust.X, -1.5, 0, -1.5);
    }
    

    Final result

    Final result - Top left

    Final fixed result - Bottom right

    The pointy part now adjusts horizontally when tooltip is near the right of the screen, and vertically when tooltip is near the bottom of the screen.

    0 讨论(0)
提交回复
热议问题