C# WPF:更改工具提示的放置目标



我正在尝试将工具提示的放置目标更改为可视化树上方的窗口,以便在该窗口中具有自定义的工具提示剪切效果。我已经连接了除放置目标之外的所有内容。 下面是来自 XAML 和代码的示例...两者都不行。 此样式当前用于附加到文本框的单个工具提示。

<Style TargetType="ToolTip">
<Setter Property="ToolTipService.PlacementTarget"
Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
AncestorType={x:Type Grid }} }" />
</Style>

如果我进入代码并查看工具提示。放置目标一旦它附加到某物...它始终设置为文本框。 我已经尝试了多种使用可视化树来获取不同UIElements的方法。 似乎什么都不起作用...所以我假设我没有理解或错过一些东西。

真正让我着迷的是,如果我进入我的代码并查看工具提示的 PlacementTarget,它不会让我将其设置为其他任何内容。 例如:

var ancestors = toolTip.PlacementTarget.GetSelfAndAncestors();
foreach(var ancestor in ancestors)
{
if(var ancestor is Grid)
{
// Conditional always hits.
// Before this line, PlacementTarget is a TextBox.
toolTip.PlacementTarget = (UIElement)ancestor;  
// After the line, PlacementTarget is still a TextBox.
}
}

我做错了什么或不理解什么?

针对上下文进行编辑:自定义剪辑效果基本上只是找到最接近工具提示目标的祖先窗口,并使用它来确保工具提示永远不会超出该窗口的边界。

一个简短的示例,使用 父Window上的属性作为PlacementTarget来设置Tooltip

<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Tag="Bar">
<Window.Resources>
<ToolTip x:Key="FooToolTip">
<StackPanel>
<TextBlock Text="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}"/>
</StackPanel>
</ToolTip>
</Window.Resources>
<Grid>
<TextBlock 
Text="Foo"
ToolTip="{StaticResource FooToolTip}"
ToolTipService.PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
HorizontalAlignment="Center" VerticalAlignment="Center" Height="20" Width="50">
</TextBlock>
</Grid>
</Window>

编辑

为了回答您的问题,

第一个代码段以错误的方式使用工具提示服务:

类附加属性用于确定工具提示的位置、行为和外观。这些属性是在定义工具提示的元素上设置的。

应用在样式中:

<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Tag="Bar">
<Window.Resources>
<ToolTip x:Key="FooToolTip">
<StackPanel>
<TextBlock Text="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}"/>
</StackPanel>
</ToolTip>
<Style x:Key="ToolTipStyle">
<Setter Property="ToolTipService.ToolTip" Value="{StaticResource FooToolTip}"/>
<Setter Property="ToolTipService.PlacementTarget" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</Window.Resources>
<Grid>
<TextBlock 
Text="Foo" Style="{StaticResource ToolTipStyle}"
HorizontalAlignment="Center" VerticalAlignment="Center" Height="20" Width="50">
</TextBlock>
</Grid>
</Window>

至于代码隐藏中的第二个代码片段,一旦ToolTip打开,您将无法设置PlacementTarget,当ToolTip关闭时,PlacementTarget为空。正如@mm8所指出的,这与ToolTipPlacementTarget在不同的视觉树中有关,因为ToolTip会生成 独树一帜的Window

最新更新