【问题标题】:Not able to override button style from app.xaml in WPF无法从 WPF 中的 app.xaml 覆盖按钮样式
【发布时间】:2023-03-14 12:34:01
【问题描述】:

我陷入了一个非常奇怪的问题,我找不到解决方案。我尝试了几乎所有可能的方法(甚至删除并重新创建解决方案)来解决这个问题。

问题

我正在尝试覆盖 WPF 应用程序中的默认控件样式。我在App.xaml 中定义了所有资源和样式。问题是,按钮前景色没有覆盖运行时。令人惊讶的是,它在 VS 设计器中显示覆盖的颜色(白色),但是当我运行应用程序时,它变成黑色(可能是默认值)。

应用中没有其他代码可以更改按钮样式。

附加信息:按钮位于用户控件中,并且加载在 MainWindow 的 ContentControl 上。

<SolidColorBrush x:Key="WhiteBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="BlackBrush" Color="#000000"/>
<SolidColorBrush x:Key="ActiveBrush" Color="#3A71C5"/>
<SolidColorBrush x:Key="HoverBrush" Color="#0071C5"/>
<SolidColorBrush x:Key="PressBrush" Color="#3A8BF4"/>
<SolidColorBrush x:Key="DefaultBrush" Color="#0071F9"/>
<SolidColorBrush x:Key="DisabledBrush" Color="#F4F4F4"/>


<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{StaticResource ActiveBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource WhiteBrush}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="{StaticResource HoverBrush}"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="{StaticResource PressBrush}"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="{StaticResource DisabledBrush}"/>
        </Trigger>
    </Style.Triggers>

</Style>

VS Designer 中的按钮

应用运行时中的按钮

【问题讨论】:

    标签: c# wpf xaml wpf-style app.xaml


    【解决方案1】:

    问题可能是您有一些其他样式应用于按钮的某些嵌套控件(例如TextBlock)。

    我将您的 sn-p 粘贴到示例 WPF 应用程序中,并将 Button 包装在自定义 UserControl 中。我对其进行了测试,并在设计视图和运行时均正确显示。

    然后我在App.xaml中添加了如下样式:

    <Style TargetType="{x:Type TextBlock}">
         <Setter Property="Foreground" Value="Red"/>
    </Style>
    

    并且按钮显示红色文本。

    所以问题可能是 other 控件的其他样式覆盖了您的 Button 模板的某些部分。


    编辑

    一种可能的解决方案是在控件本身中显式定义 Button 内容:

    <Button>
        <TextBlock Foreground="{StaticResource WhiteBrush}">Test</TextBlock>
    </Button>
    

    可能有更优雅的方法可以做到这一点,但我目前想不出其他任何方法。

    【讨论】:

    • 感谢您的回复。你会提出任何解决方案吗?当我们有这种情况时如何实现这一点(两种样式来更改默认控件样式(按钮和文本块一起))?
    • 我编辑了我的答案以添加一个可能的解决方案。我希望它有所帮助。
    • 感谢您的回答。有没有办法通过更改样式或模板来实现这一点?我不想更改所有 UI 按钮。 :( 我正在尝试为应用程序创建主题。
    • 如果您确定按钮中只有文本,您可以直接应用我在ControlTemplate 中定义的Style 中提出的解决方案。这不是一个非常好的解决方案,但它应该可以工作,直到其他人提出更好的方法。
    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多