c# - RelativeSource 绑定(bind)适用于 Style 但不适用于 ControlTemplate

标签 c# wpf xaml data-binding

我的 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/

相关文章:

c# - 如何使用嵌入式 View 模型

wpf - 每个单元格绑定(bind)一个数据网格一个对象

c# - ComboBox : Use Usercontrol to display each item 中的数据绑定(bind)

c# - 性能调整 C# 排列和 SHA1 代码

C#/WPF 应用程序抛出 ObjectDisposedException;为什么我无法捕获或获取堆栈跟踪?

c# - 动态构建 Func<t,t> 列表 - 然后应用于 linq 查询

c# - 无法正确绑定(bind) DataGrid 和 ObservableCollection

c# - Linq to Entities - 是否可以在对数据库的单个查询中实现这一点?

c# - 以编程方式向 TreeViewItem 添加内容

xaml - Bing MapControl WP7 XAML 数据绑定(bind)中心