Bind to wpf custom control dependency property for tooltip?

感情迁移 提交于 2019-12-01 13:17:01

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.

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>

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.

Did you also add the variable to your codebehind?

Like:

public bool IsAlert
    {
        get { return (bool)GetValue(IsAlertProperty); }
        set { SetValue(IsAlertProperty, value); }
    }

Using this should allow you to bind it without any hierarchic information. By the way, you can check easily if your binding is working by setting a breakpoint within the converter.

Writing a CustomControl is unlike creating a basic UserControl. For a start, you don't have your own XAML file to define your control... you have to share the generic.xaml file. This often causes new developers problems when it comes to either data binding, or event handling. However, the solution is simple.

All you need to do is to use a RelativeSource Binding, not to the TemplatedParent, but to your control's property. Try this:

<ToolTip Visiblity="{Binding Path=IsAlert, RelativeSource={RelativeSource 
    AncestorType={x:Type YourXamlNamespacePrefix:AlertControl}}, 
    Converter={StaticResource BooleanToVisiblityConverter}">
    <!-- Tooltip content goes here -->
</ToolTip>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!