wpf – 如何定位工具提示底部中心

我正在尝试定位我的工具提示,以便它位于我的目标对象的底部和中心.我可以通过ToolTipService.Postion =“Bottom”将它定位在底部,但是如何将它定位在中心?
我同意,可用于定位工具提示的选项有点受限.我认为你必须将Placement =“Bottom”和Horizo​​ntalOffset结合起来才能获得Bottom / Center定位.

要使ToolTip相对于您可以使用的PlacementTarget居中
(PlacementTarget.ActualWidth / 2.0) – (ToolTip.ActualWidth / 2.0)

<Button Content="Test">
    <Button.ToolTip>
        <ToolTip Content="ToolTip Text"
                 Placement="Bottom">
            <ToolTip.HorizontalOffset>
                <MultiBinding Converter="{StaticResource CenterToolTipConverter}">
                    <Binding RelativeSource="{RelativeSource Self}" Path="PlacementTarget.ActualWidth"/>
                    <Binding RelativeSource="{RelativeSource Self}" Path="ActualWidth"/>
                </MultiBinding>
            </ToolTip.HorizontalOffset>
        </ToolTip>
    </Button.ToolTip>
</Button>

CenterToolTipConverter

public class CenterToolTipConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.FirstOrDefault(v => v == DependencyProperty.UnsetValue) != null)
        {
            return double.NaN;
        }
        double placementTargetWidth = (double)values[0];
        double toolTipWidth = (double)values[1];
        return (placementTargetWidth / 2.0) - (toolTipWidth / 2.0);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

如果你需要居中几个工具提示,你可以使用类似的样式

<Style x:Key="centeredToolTip" TargetType="ToolTip">
    <Setter Property="HorizontalOffset">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource CenterToolTipConverter}">
                <Binding RelativeSource="{RelativeSource Self}" Path="PlacementTarget.ActualWidth"/>
                <Binding RelativeSource="{RelativeSource Self}" Path="ActualWidth"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

<!-- ... -->

<Button Content="Test">
    <Button.ToolTip>
        <ToolTip Style="{StaticResource centeredToolTip}"
                 Placement="Bottom"
                 Content="ToolTip Text"/>
    </Button.ToolTip>
</Button>
翻译自:https://stackoverflow.com/questions/10972335/how-to-position-tooltip-bottom-center

转载注明原文:wpf – 如何定位工具提示底部中心