我正在创建一个自定义按钮,该按钮通常显示稍微褪色的文本,并在 MouseOver
或 MouseDown
上显示全强度文本。我在控件的 Generic.xaml
中定义了两个资源来表示这些文本颜色的画笔:
<!-- Text Brushes -->
<SolidColorBrush x:Key="NormalTextBrush" Color="Black" />
<SolidColorBrush x:Key="FadedTextBrush" Color="Gray" />
该控件可以在该配置中编译并正常工作。
但我想让控件用户使用自定义控件的 Foreground
属性来设置文本颜色。因此,我将资源声明更改为:
<!-- Text Brushes -->
<SolidColorBrush x:Key="NormalTextBrush" Color="{Binding Path=Foreground, RelativeSource={RelativeSource TemplatedParent}}" />
<SolidColorBrush x:Key="FadedTextBrush" Color="{Binding Path=Foreground, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ColorConverter}, ConverterParameter='1.2'}" />
第二个声明使用 HSL
值转换器来淡化文本颜色。
现在控件不起作用,我在输出窗口中收到以下错误:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Foreground; DataItem='TaskButton' (Name='Button1'); target element is 'SolidColorBrush' (HashCode=38118303); target property is 'Color' (type 'Color')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Foreground; DataItem=null; target element is 'SolidColorBrush' (HashCode=47449297); target property is 'Color' (type 'Color')
我不确定数据错误
告诉我什么。谁能告诉我发生了什么事以及如何解决它?感谢您的帮助。
最佳答案
RelativeSource TemplatedParent
仅 (IIRC) 在控件模板中有意义,它指的是应用该模板的控件实例的属性。
UserControl
的内容不是 UserControl
的模板。因此,此绑定(bind)不会将父 UserControl
视为可行的目标。
错误消息是指 SolidColorBrush
没有模板;它不扩展 System.Windows.Controls.Control,这是(大多数)所有模板化 UI 控件的基本类型。请参阅Control.Template
有关模板的更多信息。
您想要做的是设置FindAncestor
的相对源。
{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}
这将沿着视觉(或者逻辑?)树查找 UserControl
类型的第一个祖先,然后绑定(bind)到名为 Foreground
的公共(public)属性。
但是如果SolidColorBrush
被定义为Resource
,这将不起作用。资源不是视觉(或逻辑树,或两者?仍然不清楚)的一部分,因此 RelativeSource
绑定(bind)将无法遍历树的祖先。
您必须直接在任何您希望与 UserControl
具有相同前景色的控件上使用绑定(bind)。
关于wpf - 将资源绑定(bind)到自定义控件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4924621/