【问题标题】:Default custom ControlTemplate is not applied when using Style使用 Style 时不应用默认自定义 ControlTemplate
【发布时间】:2011-01-25 00:30:24
【问题描述】:

我为 Button 创建了一个默认样式,包括一个自定义 ControlTemplate,如下所示:

<Style TargetType="{x:Type Button}">
    <Setter Property="OverridesDefaultStyle" Value="True"/>
    <Setter Property="Background" Value="White"/>
    <Setter Property="BorderBrush" Value="Black"/>
    <!-- ...other property setters... -->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid x:Name="gridMain">
                    <!-- some content here -->
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

此样式已添加到我的共享 ResourceDictionary 中,每个控件都会加载该样式。现在,正如预期的那样,此样式/模板已应用于我的所有按钮,但不适用于本地使用不同样式的那些按钮。例如,我希望我的“确定”、“应用”和“取消”按钮有一定的余量。因此,我定义了以下样式:

<Style x:Key="OKApplyCancelStyle" TargetType="{x:Type Button}">
    <Setter Property="Margin" Value="4,8"/>
    <Setter Property="Padding" Value="8,6"/>
    <Setter Property="MinWidth" Value="100"/>
    <Setter Property="FontSize" Value="16"/>
</Style>

...并使用 StaticResource 将该样式应用于我的按钮:

<Button Content="OK" Style="{StaticResource OKApplyCancelStyle}"/>

对我来说,预期的结果是仍然会应用上面的 ControlTemplate,使用“OKApplyCancelStyle”中的 Margin、Padding、MinWidth 和 FontSize 值。但这种情况并非如此。改为使用默认的 Windows ControlTemplate,使用样式中的值。

这是典型的行为吗?本地样式真的会覆盖自定义 ControlTemplate 吗?如果是这样,我怎样才能实现我想要的行为? IE。即使在本地定义了样式,仍然使用我的自定义 ControlTemplate?

提前非常感谢, 呵呵。

【问题讨论】:

    标签: wpf controltemplate


    【解决方案1】:

    这里完全凭记忆,但有点像(或非常像)

    <Style x:Key="OKApplyCancelStyle" BasedOn="{StaticResource {x:Type Button}}">
    <!--Style here-->
    </Style>
    

    可能会起作用。

    【讨论】:

    • 是的,这确实有效。 :) 非常感谢!但是,我仍然想知道是否真的没有办法覆盖控件的默认主题模板(没有 BasedOn)。我想,这就是“OverridesDefaultStyle”属性的用途。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多