簡體   English   中英

無法從WPF中的app.xaml覆蓋按鈕樣式

[英]Not able to override button style from app.xaml in WPF

我陷入了一個非常奇怪的問題,無法找到解決方案。 我嘗試了幾乎所有可能的方法(甚至刪除並重新創建解決方案)來解決此問題。

問題

我試圖覆蓋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>

可能有更優雅的方法可以執行此操作,但是目前我無法提出其他任何建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM