在逻辑或可视树中查找工具提示弹出窗口

假设我有一个在XAML中指定样式的ToolTip ,如下所示:

   

鉴于我有一个Button的引用和ToolTip正在显示,我如何找到ToolTipPopup (后来寻找它的视觉子代,例如TxbTitle )?

更新:

根据pushpraj的回答,我能够抓住(完整)可视化树,它看起来像这样:

 System.Windows.Controls.Primitives.PopupRoot System.Windows.Controls.Decorator System.Windows.Documents.NonLogicalAdornerDecorator System.Windows.Controls.ToolTip System.Windows.Controls.StackPanel System.Windows.Controls.TextBlock (TxbTitle) System.Windows.Controls.ContentPresenter System.Windows.Controls.TextBlock System.Windows.Documents.AdornerLayer 

在这里,我可以找到TxbTitle TextBlock

(像这样的逻辑树:)

 System.Windows.Controls.Primitives.Popup System.Windows.Controls.ToolTip System.String 

然而,pushpraj的答案是基于我可以掌握ToolTip实例。 我得到的只是Button ,而Button.ToolTip属性返回字符串"Likes to be clicked" ,而不是ToolTip实例。

更具体地说,问题是,当我得到的只是Button时,我能以某种方式获得ToolTip Popup吗?

(疯狂的想法:有没有办法枚举所有打开的Popup ?)

ToolTip是一种托管工具提示内容的Popup

由于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

  

我已将新创建的附加属性添加到工具提示样式

从后面的代码中检索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添加一个setter, ToolTipHelper.IsEnabledProperty相同的样式注入窗口的资源

因此,当需要显示工具提示时,属性更改处理程序OnEnable将在ToolTipHelper类中调用。 并且处理程序中的依赖项对象将是您可能进一步操作的实际工具提示实例。