WPF:影响样式触发条件的边框

时间:2019-02-13 14:07:05

标签: wpf wpf-style

我正在创建自己的单选按钮。我只想更改它的图形。他们看起来像他们想要的样子,但是我无法更改IsChecked的外观...这就是我到目前为止所拥有的

<RadioButton x:Class="gMaterialWPF.MaterialRadioButton" [....]>
    <RadioButton.Style>
        <Style TargetType="{x:Type RadioButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RadioButton}">
                        <Border x:Name="backPanel" 
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="10">

                        <ContentPresenter HorizontalAlignment="Center"
                                          VerticalAlignment="Center"
                                          Content="{TemplateBinding Content}"
                                          />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </RadioButton.Style>
</RadioButton>

问题是如何访问backPannel来更改<Trigger Property="IsChecked"的颜色?我尝试使用TargetName,但是找不到那边的面板:(

2 个答案:

答案 0 :(得分:1)

  

我尝试了TargetName,但找不到那里的面板:(

如果要使用ControlTemplate属性引用Border元素,则需要将触发器移至TargetName

<Style TargetType="{x:Type RadioButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type RadioButton}">
                <Border x:Name="backPanel" 
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="10">

                    <ContentPresenter HorizontalAlignment="Center"
                                          VerticalAlignment="Center"
                                          Content="{TemplateBinding Content}"
                                          />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="backPanel" Property="Background" Value="Red"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但是由于您在示例中使用BackgroundBorder元素的Background属性绑定到RadioButton的{​​{1}}属性,因此您真的不必使用TemplateBinding

答案 1 :(得分:0)

您可以从RadioButton.IsChecked的{​​{1}}访问Style.Triggers

Border