You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF自定义ToolTip窗口最大化时右侧按钮位置偏移问题求助

问题原因

当应用程序最大化后,ToolTip靠近屏幕右侧边界时,WPF会自动调整ToolTip的位置(避免其超出可视区域),但你自定义模板中的指示三角使用了固定的Margin="6,2,0,0"和HorizontalAlignment="Left",无法跟随ToolTip的位置调整同步变化,最终导致三角与按钮错位。

解决方案

修改ToolTip的ControlTemplate,将指示三角设置为水平居中,使其始终与ToolTip内容区域的顶部中心对齐。这样无论ToolTip被WPF调整到什么位置,三角都会自动对齐按钮下方。

修改后的完整XAML代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Style TargetType="ToolTip">
        <Setter Property="Background" Value="#404040" />
        <Setter Property="Foreground" Value="#FFFFFF" />
        <Setter Property="Placement" Value="Bottom" />
        <Setter Property="HasDropShadow" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ToolTip">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>

                        <Path
                            Grid.Row="0"
                            Width="12"
                            Height="8"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Bottom"
                            Data="M9.6 4.53333C9.8 4.26667 10.2 4.26667 10.4 4.53333L16 12H4L9.6 4.53333Z"
                            Fill="{TemplateBinding Background}"
                            Stretch="Fill" />

                        <Border
                            Grid.Row="1"
                            Background="{TemplateBinding Background}"
                            BorderBrush="Transparent"
                            BorderThickness="0"
                            CornerRadius="3">
                            <TextBlock
                                Padding="8"
                                FontSize="12"
                                FontWeight="Normal"
                                Foreground="{TemplateBinding Foreground}"
                                Text="{TemplateBinding Content}"
                                TextWrapping="Wrap" />
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
关键修改点
  1. 将原Grid改为带两行定义的布局,分离三角与内容区域的布局逻辑
  2. 三角的HorizontalAlignment设为Center,使其始终位于ToolTip内容区域的顶部中心
  3. 三角的VerticalAlignment设为Bottom,让三角底部与下方Border顶部紧密衔接,消除间隙

修改后,无论ToolTip是否因屏幕边界被调整位置,指示三角都会自动对齐按钮的正下方,解决边缘错位问题。

内容的提问来源于stack exchange,提问作者Gururaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:43:22