0
按照必要的「Minimal, Complete and Verifiable」 -在自定義控件上使用RelativeSource綁定ToolTip內容的正確方法是什麼?
這是「自定義控件」來重現問題。
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')
我如何調整我的工具提示綁定,這樣它會拿起控件的屬性?
它就在那裏。優秀。謝謝你,先生。 – Will