Search code examples
wpfbuttonbackgroundstylesisenabled

Disable Button but keep the color of the background


i have the following button style which works fine:

<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="Border"
                        CornerRadius="2" BorderThickness="1"
                        Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}">
                        <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" />
                            <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" />
                            <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

with more styles defined at the button itself i change the buttons background (green for active)

<Button>
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding MainStatus.Restart}" Value="true">
                    <Setter Property="Background" Value="LimeGreen" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

now if i disable the button, the button gets gray, because of the template. is there a way of making the current background more 'gray' but keeping the base color. so if the button was green, the color remains basically green?


Solution

  • Instead of setting background gray, you can set opacity to give it a disabled look (this will retain your background) something like this:

    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <!--<Setter TargetName="Border" Property="Background"
                        Value="{StaticResource DisabledBackgroundBrush}" />-->
            <Setter TargetName="Border" Property="Opacity" Value="0.4"/>
            <Setter TargetName="Border" Property="BorderBrush"
                    Value="{StaticResource DisabledBorderBrush}" />
            <Setter Property="Foreground"
                    Value="{StaticResource DisabledForegroundBrush}"/>
        </Trigger>
    </ControlTemplate.Triggers>