无法从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中的按钮

在此处输入图片说明

应用程式执行阶段中的按钮

在此处输入图片说明

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

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

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

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

并且按钮显示红色文本。

因此,问题可能是其他控件的某些其他样式覆盖了Button模板的某些部分


编辑

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

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

可能有更优雅的方法可以执行此操作,但是目前我无法提出其他任何建议。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章