簡體   English   中英

RelativeSource綁定適用於Style但不適用於ControlTemplate

[英]RelativeSource binding works from Style but not ControlTemplate

我的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 ,它來自。 在此示例中,綁定無法找到該屬性。

找不到與引用'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>

如何在第一個示例中修復綁定? 優選地,我想在用戶控件中的每個控件的實例上不需要其他屬性。

兩個建議:

如果ControlTemplate是Style的一部分,您可以使用綁定將ToggleButton的BorderBrush屬性設置為SolidColorBrush ,並在TemplateBinding中使用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,則解決方法是綁定到Brush屬性而不是Color屬性:

<ControlTemplate TargetType="{x:Type ToggleButton}">
    <Border BorderBrush="{Binding Path=BorderBrushProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" BorderThickness="10">
        <TextBlock>....</TextBlock>
    </Border>
</ControlTemplate>

如果您使用Background而不是BorderColor,它可以工作。 BorderColor是你自己的財產嗎?

<Window.Resources>
<ControlTemplate x:Key="template" TargetType="{x:Type ToggleButton}">
    <Border>
        <Border.BorderBrush>
                <SolidColorBrush Color="{Binding Path=Background,RelativeSource={RelativeSource AncestorType=UserControl}}" />
        </Border.BorderBrush>
    </Border>
</ControlTemplate>
</Window.Resources>

<UserControl Background="Aqua">
    <ToggleButton Template="{StaticResource template}"></ToggleButton>

</UserControl>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM