wpf - 将资源绑定(bind)到自定义控件属性

标签 wpf wpf-controls binding

我正在创建一个自定义按钮,该按钮通常显示稍微褪色的文本,并在 MouseOverMouseDown 上显示全强度文本。我在控件的 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/

相关文章:

c# - WPF 拖放源代码

wpf-controls - WPF 用户控件中托管的 CefSharp Wpf 浏览器的 UI 自动化

wpf - TextBlock:Text和StringFormat的绑定(bind)

javascript - html 未在 ng-repeat 中呈现

ASP.NET 3.5 绑定(bind)到 XML 字符串

c# - 带有是和否按钮的消息框

c# - 如何避免 WPF 验证中的错误图标与其他元素重叠

c# - 可以在代码中使用 Blend SDK 类,但不能使用 XAML (Prism Desktop)

c# - WPF 中列表框的 SetBinding

c# - 水平方向的 ItemsControl