且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绑定到wpf自定义控件依赖项属性以获得工具提示吗?

更新时间:2021-10-16 02:51:26

何时它涉及到WPF ToolTip ,您必须了解它不像其他控件一样属于VisualTree。它仅在有必要创建它时才起作用,也就是鼠标悬停在控件上时。目前,WPF将创建 ToolTip ,但不会将其放置为 AlertControl 的子元素,这就是为什么 RelativeSourceMode s( TemplatedParent FindAncestor )无效。

When it comes to a WPF ToolTip, you have to understand that it is not part of the VisualTree the same way other controls are. It only comes into play when it is necessary to create it, which is when your mouse is hovering over the control. At this time, WPF will create the ToolTip, but it will not place it as a child element of the AlertControl, which is why both of the RelativeSourceModes (TemplatedParent and FindAncestor) did not work.

虽然有一个节省的宽限期,但这就是 ToolTip.PlacementTarget 属性。

There is one saving grace though, and that is the ToolTip.PlacementTarget property.

<ToolTip Visibility="{Binding Path=PlacementTarget.(local:AlertControl.IsAlert),
                              RelativeSource={RelativeSource Self},
                              Converter={...}}">
    ...
<ToolTip>

您在这里正在告诉WPF BindingExtension 绑定到名为 PlacementTarget 的属性(恰好是创建 UIElement > ToolTip ,根据您的情况选择 AlertControl ),并且您打算从 ToolTip $找到该属性。 c $ c>本身(不是 ToolTip DataContext )。除此之外,您还计划使用 IValueConverter 。此外,完整的未解析的 PropertyInfo 不仅会在 ToolTip $ 中查找 PlacementTarget 。 c $ c>,但还会检查从 PlacementTarget 返回的对象是否可以转换为 AlertControl 的类型。 ,然后访问其 IsAlert CLR属性。我本可以很容易地完成 Path = PlacementTarget.IsAlert 的工作,但经过反思,它还是可以的,但我想明确指出应该访问IsAlert属性。来自 AlertControl 类型。

What you are doing here is telling the WPF BindingExtension to bind to the property named PlacementTarget (which happens to be the UIElement that created the ToolTip, the AlertControl in your situation), and you are stating to locate this property from the ToolTip itself (not the DataContext of the ToolTip). Beyond that, you are also planning to use a IValueConverter. Additionally, the full unparsed PropertyInfo not only looks for the PlacementTarget on the ToolTip, but also checks to see if the object returned from PlacementTarget can be cast as a type of AlertControl, and then access its IsAlert CLR property. I could have easily have done Path=PlacementTarget.IsAlert and, with reflection, it would have worked out just fine, but I prefer to explicitly state that the IsAlert property should be accessed from a type of AlertControl.