c# - 无法从 WPF 中的 app.xaml 覆盖按钮样式
问题描述
我陷入了一个非常奇怪的问题,我找不到解决方案。我尝试了几乎所有可能的方法(甚至删除并重新创建解决方案)来解决这个问题。
问题
我正在尝试覆盖 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 中的按钮
应用程序运行时中的按钮
解决方案
The issue could be that you have some other style which gets applied to some nested control of your button (e.g. TextBlock
).
I pasted your snippet in a sample WPF app and wrapped a Button
in a custom UserControl
. I tested it and showed correctly in both design view and runtime.
Then I added the following style in App.xaml
:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Red"/>
</Style>
and the button was showing red text.
So the problem could be some other style for other controls which is overriding some parts of your Button
template.
EDIT
A possible solution could be to explicitly define the Button content in the control itself:
<Button>
<TextBlock Foreground="{StaticResource WhiteBrush}">Test</TextBlock>
</Button>
There are probably more elegant ways to do this, but I couldn't come up with anything else at the moment.
推荐阅读
- python - 将 QFileSystemModel 与 QSortFilterProxyModel 组合时崩溃
- angular - Angular:防止用户在文本输入中打印
- java - 在 evrey 测试用例之前在 android studio 中使用 espresso 清除/删除缓存
- java - 如何指定仅需要使用 ReactiveCassandraRepository 插入的实体的少数文件
- c++ - 如何使用opencv/c++检测图像中最大的正方形?
- java - 等待 CompletableFuture 列表
- python - 无需绘制就可以获得 cv2.line 像素坐标(寻找速度增加)?
- amazon-web-services - Dynamodb 等价于 SQL 案例
- postgresql - 尝试启用与数据库的删除连接后,EDB PostgreSQL 重新启动服务失败
- asp.net-core - API Endpoints 缺少具有空值的属性?