问题描述
我正在尝试定位我的工具提示,使其位于目标对象的底部和中心.我可以通过 ToolTipService.Postion="Bottom"
将它定位在底部,但是如何将它定位在中心?
I'm trying to position my tooltip so that it would be on the bottom and center of my target object. I can position it to be just on the bottom by ToolTipService.Postion="Bottom"
, but how to position it to be also on the center?
推荐答案
我同意,可用于定位 ToolTip
的选项有点有限.我认为你必须结合 Placement="Bottom"
和 HorizontalOffset
来获得底部/中心定位.
I agree, the options available for positioning a ToolTip
are a little limited. I think you'll have to combine Placement="Bottom"
with HorizontalOffset
to get Bottom/Center positioning.
要使 ToolTip
相对于 PlacementTarget
居中,您可以使用(PlacementTarget.ActualWidth/2.0) - (ToolTip.ActualWidth/2.0)
To center the ToolTip
relative to the PlacementTarget
you can use(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();
}
}
如果您需要将多个 ToolTips
居中,您可以使用 Style
之类的
If you need to center several ToolTips
you could use a Style
like
<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>
这篇关于如何定位工具提示底部中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!