在自定义控件上使用RelativeSource绑定ToolTip内容的正确方法是什么?

时间:2017-08-27 20:17:08

标签: c# wpf xaml binding relativesource

根据必要条件“Minimal, Complete and Verifiable” -

这是重现问题的“自定义控件”。

XAML:

<TextBlock
    x:Class="FooTips.FooTipControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:l="clr-namespace:FooTips"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    d:DesignHeight="300" d:DesignWidth="300" mc:Ignorable="d"
    Text="{Binding FooTipText, RelativeSource={RelativeSource Self}}">
    <TextBlock.ToolTip>
        <ToolTip Content="{Binding FooTipText, RelativeSource={RelativeSource AncestorType={x:Type l:FooTipControl}, Mode=FindAncestor}}" />
    </TextBlock.ToolTip>
</TextBlock>

代码:

using System.Windows;

namespace FooTips {
    /// <summary>
    /// Interaction logic for FooTipControl.xaml
    /// </summary>
    public partial class FooTipControl {
        public static readonly DependencyProperty
            FooTipTextProperty = DependencyProperty.Register(
                "FooTipText", typeof( string ), typeof( FooTipControl ) );

        public FooTipControl( ) {
            InitializeComponent( );
        }

        public string FooTipText {
            get => this.GetValue( FooTipTextProperty ).ToString( );
            set => this.SetValue( FooTipTextProperty, value );
        }
    }
}

放入窗口(或其他)并设置FooTipText = "FOO"(或其他)。

文本显示在控件中,但构建输出显示以下绑定错误 -

System.Windows.Data Error: 4 :
    Cannot find source for binding with reference
        'RelativeSource FindAncestor,
        AncestorType='FooTips.FooTipControl',
        AncestorLevel='1''.
    BindingExpression:
        Path=FooTipText;
        DataItem=null;
        target element is 'ToolTip' (Name='');
        target property is 'Content' (type 'Object')

如何调整我的Tooltip绑定,以便它能够获取控件属性?

1 个答案:

答案 0 :(得分:2)

这有效:

<TextBlock x:Class="FooTips.FooTipControl"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:l="clr-namespace:FooTips"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            d:DesignHeight="300" d:DesignWidth="300" mc:Ignorable="d"
            Text="{Binding FooTipText, RelativeSource={RelativeSource Self}}"
            ToolTip="{Binding FooTipText, RelativeSource={RelativeSource Self}}">
</TextBlock>

......这也是:

<TextBlock.ToolTip>
    <ToolTip Content="{Binding PlacementTarget.FooTipText, RelativeSource={RelativeSource Self}}" />
</TextBlock.ToolTip>