如果给定x:Key,则样式会产生不同的渲染结果

时间:2015-09-02 08:10:58

标签: c# wpf controltemplate

如果给定x:Key

,则样式会产生不同的渲染结果

我为ControlTemplate设置了以下样式和ToggleButtons,它们可以按照我的意愿运作。

<Style TargetType="RadioButton" BasedOn="{StaticResource {x:Type ToggleButton}}"/>
<ControlTemplate TargetType="RadioButton" x:Key="RadioTemplate">
    <RadioButton IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsChecked, Mode=TwoWay}">
        <RadioButton.Content>
            <Viewbox StretchDirection="DownOnly" Stretch="Uniform">
                <ContentControl Content="{TemplateBinding Content}"/>
            </Viewbox>
        </RadioButton.Content>
    </RadioButton>
</ControlTemplate>

但是,当我向x:Key提供StyleRadioButton中的ControlTemplate会继承样式,如下所示, 渲染结果与上面代码给出的结果不同。

<Style TargetType="RadioButton" BasedOn="{StaticResource {x:Type ToggleButton}}" x:Key="RadioStyle"/>
<ControlTemplate TargetType="RadioButton" x:Key="RadioTemplate">
    <RadioButton Style="{StaticResource RadioStyle}"
                 IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsChecked, Mode=TwoWay}">
        <RadioButton.Content>
            <Viewbox StretchDirection="DownOnly" Stretch="Uniform">
                <ContentControl Content="{TemplateBinding Content}"/>
            </Viewbox>
        </RadioButton.Content>
    </RadioButton>
</ControlTemplate>

有人能告诉我为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

MSDN文档:

  

TargetType属性设置为RadioButton类型而不设置x:Key会隐式将x:Key设置为{x:Type RadioButton }。这也意味着,如果您为上述样式提供除x:Key以外的任何值的{x:Type RadioButton}值,则样式不会自动应用于所有RadioButton元素。相反,您需要将样式明确地应用于RadioButton元素,如"{StaticResource RadioStyle}"

答案 1 :(得分:1)

指定密钥时需要使用密钥。 带键的Style不会自动反映到togglebuttons。

相关问题