WPF 按钮样式未应用于子元素

标签 wpf xaml

我有一个这样的按钮样式

<Style x:Key="NormalButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid x:Name="ContentSite">
                    <Grid x:Name="ContainerGrid">
                        <ContentPresenter x:Name="Presenter" Style="{DynamicResource NormalButtonTextStyle}"/>
...

ContentPresenter 的样式在哪里
<Style x:Key="NormalButtonTextStyle" BasedOn="{StaticResource DefaultFontStyle}">
    <Setter Property="TextElement.Foreground" Value="{DynamicResource NormalTextOnDarkBackgroundBrush}" />
...

然后我像这样定义了我的按钮
<Button Style="{StaticResource NormalButtonStyle}">
    <Button.Content>
        <TextBlock Text="Cancel"/>
...

但是 TextBlock 并没有以 NormalButtonTextStyle 结束风格。我在运行时检查了元素,内容展示者肯定有正确的文本前景,但随后子 TextBlock 最终继承了完全不同的东西,并获得了 ControlTextBrush 的前景。 .

我是否误解了样式如何应用于子元素?我应该如何定义按钮以便正确应用样式?

最佳答案

添加 <Setter />Button style :

<Style x:Key="NormalButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="TextElement.Foreground" Value="{DynamicResource NormalTextOnDarkBackgroundBrush}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid x:Name="ContentSite">
                    <Grid x:Name="ContainerGrid">
                        <ContentPresenter x:Name="Presenter" />
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

关于WPF 按钮样式未应用于子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489552/

相关文章:

c# - WPF动态数折线图

c# - 在 xamarin 表单中选择 ListView 项时如何打开另一个页面?

WPF 应用程序在通过 doPDF 打印机打印到文件后引发异常

c# - 如何绕过应用程序范围设置为只读?

c# - 将单个 WPF 控件绑定(bind)到多个项目

wpf - 使用 MVVM ViewModel 将 XDocument 显示为 WPF TreeView

c# - 为什么在 WPF 中将 INotifyPropertyChanged 与绑定(bind)一起使用?

xaml - 将 StackPanel 背景设置为 WP7 选定的强调(主题)颜色

xaml - ElementName 绑定(bind)不解析属性

C#/XAML winRT 应用导出 PDF