A ToolTip
是一种Popup
承载工具提示内容
由于弹出窗口托管在单独的窗口中,因此它有自己的逻辑和可视树
以下是工具提示的视觉和逻辑树,供您参考
视觉树
System.Windows.Controls.Primitives.PopupRoot
System.Windows.Controls.Decorator
System.Windows.Documents.NonLogicalAdornerDecorator
System.Windows.Controls.ToolTip
逻辑树
System.Windows.Controls.Primitives.Popup
System.Windows.Controls.ToolTip
注意:由于弹出窗口有自己的根目录,因此可能无法从主窗口的视觉或逻辑树访问它。
查找工具提示的弹出窗口
我已使用附加属性来查找工具提示的弹出窗口
namespace CSharpWPF
{
public class ToolTipHelper : DependencyObject
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
// Using a DependencyProperty as the backing store for IsEnabled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ToolTipHelper), new PropertyMetadata(false,OnEnable));
private static void OnEnable(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ToolTip t = d as ToolTip;
DependencyObject parent = t;
do
{
parent = VisualTreeHelper.GetParent(parent);
if(parent!=null)
System.Diagnostics.Debug.Print(parent.GetType().FullName);
} while (parent != null);
parent = t;
do
{
//first logical parent is the popup
parent = LogicalTreeHelper.GetParent(parent);
if (parent != null)
System.Diagnostics.Debug.Print(parent.GetType().FullName);
} while (parent != null);
}
}
}
xaml
<Button Content="Click me" ToolTip="Likes to be clicked">
<Button.Resources>
<Style TargetType="{x:Type ToolTip}" BasedOn="{StaticResource {x:Type ToolTip}}"
xmlns:l="clr-namespace:CSharpWPF">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="HasDropShadow" Value="True" />
<Setter Property="l:ToolTipHelper.IsEnabled" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToolTip}">
<StackPanel Background="Wheat" Height="200" Width="200">
<TextBlock x:Name="TxbTitle" FontSize="24" Text="ToolTip" Background="BurlyWood" />
<ContentPresenter />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
</Button>
我已将新创建的附加属性添加到工具提示样式<Setter Property="l:ToolTipHelper.IsEnabled" Value="True"/>
从隐藏代码中检索 ToolTip 实例
如果您无法从 xaml 指定样式或样式模板,则后面的代码是检索工具提示实例的方法
示例代码
Style style = new Style(typeof(ToolTip), (Style)this.FindResource(typeof(ToolTip)));
style.Setters.Add(new Setter(ToolTipHelper.IsEnabledProperty, true));
this.Resources.Add(typeof(ToolTip), style);
上面的代码为工具提示创建了一个样式对象,并添加了一个设置器ToolTipHelper.IsEnabledProperty
并将相同的样式注入到窗口的资源中
结果属性改变了处理程序OnEnable
将在ToolTipHelper
当需要显示工具提示时类。处理程序中的依赖项对象将是您可以进一步操作的实际工具提示实例。