WPF - Default Button Disable Style When Foreground applied

If you edit Button's default template you can find the following trigger inside control template.

  <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Background" TargetName="border" Value="#FFF4F4F4"/>
                <Setter Property="BorderBrush" TargetName="border" Value="#FFADB2B5"/>
                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="#FF838383"/>
            </Trigger>

This trigger set Foreground to the content presenter using TargetName. No template binding used here. It directly assigns value. So the values you set for Foreground in Style Triggers will not be applied. You can edit the control template to achieve your requirement. This limitation not only for Foreground, for Background and BorderBrush also have this.


I am not sure I understand the question properly, because those codes posted in question should work fine. Following is a working sample to produce a Button exactly as the captured image shows. I put the Style as resource in the Button's container control -StackPanel in this case- :

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Foreground" Value="Red"/>
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Foreground" Value="#FFADADAD"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Resources>
    <Button Width="150" 
        Height="50"
        Content="Test"
        IsEnabled="True">
    </Button>
</StackPanel>

If you set the properties locally the trigger will not be able to change the value due to precedence.

Move the Foreground and IsEnabled property into the style:

<StackPanel>
<StackPanel.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Foreground" Value="Red"/>
        <Setter Property="IsEnabled" Value="True"/>
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Foreground" Value="#FFADADAD"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</StackPanel.Resources>
<Button Width="150" 
    Height="50"
    Content="Test">
</Button>

Tags:

Wpf