我的 Application.Resources
ResourceDictionary
中的一个条目是一个控件模板,精简后看起来类似于以下内容:
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border>
<Border.BorderBrush>
<SolidColorBrush Color="{Binding Path=BorderColor, RelativeSource={RelativeSource AncestorType=UserControl}" />
</Border.BorderBrush>
</Border>
</ControlTemplate>
每个 UserControl
都有它自己的属性 BorderColor
,这是从中提取的。在此示例中,绑定(bind)无法找到该属性。
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''.
但是,它在字典的另一个条目中有效:
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="BorderBrush" Value="{Binding Path=BorderColor, RelativeSource={RelativeSource AncestorType=UserControl}"/>
</Style>
如何修复第一个示例中的绑定(bind)?我最好不需要用户控件中每个控件实例的附加属性。
最佳答案
两个建议:
如果 ControlTemplate 是 Style 的一部分,您可以通过绑定(bind)将 ToggleButton 的 BorderBrush
属性设置为 SolidColorBrush
并使用 TemplateBinding
在模板中:
<Style x:Key="myStyle" TargetType="ToggleButton">
<Setter Property="BorderBrush">
<Setter.Value>
<SolidColorBrush Color="{Binding Path=BorderColor, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border BorderBrush="{TemplateBinding Background}" BorderThickness="10">
<TextBlock>....</TextBlock>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果出于某种原因你想定义一个独立的 ControlTemplate,解决方法是绑定(bind)到 Brush 属性而不是 Color 属性:
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border BorderBrush="{Binding Path=BorderBrushProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" BorderThickness="10">
<TextBlock>....</TextBlock>
</Border>
</ControlTemplate>
关于c# - RelativeSource 绑定(bind)适用于 Style 但不适用于 ControlTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007839/