我想将我的工具提示定位在目标对象的底部和中心。我可以使用 ToolTipService.Postion="Bottom"
将其定位在底部,但如何使其也处于中心位置?
我想将我的工具提示定位在目标对象的底部和中心。我可以使用 ToolTipService.Postion="Bottom"
将其定位在底部,但如何使其也处于中心位置?
我同意,定位 ToolTip
的可用选项有些有限。我认为你需要将 Placement="Bottom"
与 HorizontalOffset
结合起来,以获得底部/居中的定位。
要使 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();
}
}
如果你需要居中多个 ToolTips
,你可以使用类似下面的 Style
:
<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>
return (toolTipWidth / 2.0) - (placementTargetWidth / 2.0);
否则,工具提示将不会居中。 - ToastedSoul