Liran
Liran

Reputation: 43

WPF - change Button controltemplate background when Command.CanExecute is false

scenario: When using default implementation of button the below functionality works:

When canExeucte command is true -> the button is enabled and button background is not changed.

When CanExecute command is false -> the button is disabled and background is "grayed".

But When using Button ControlTemplate style and CanExecute is false -> the button is disabled as expected but background is not changed.

How can I change the background of the Control Template button ?

image : https://onedrive.live.com/redir?resid=3A8F69A0FB413FA4!125&authkey=!ALh_kjfxMMNzhSY&v=3&ithint=photo%2cpng

Control Template: 

 <!--button-->
    <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">

        <Border x:Name="border" CornerRadius="0" Background="Green"  BorderBrush="#FF06A6F0"  BorderThickness="1" Opacity="1"  Width="147" Height="50" >
            <ContentPresenter x:Name="contentPresenter"  
                              ContentTemplate="{TemplateBinding ContentTemplate}" 
                              Content="{TemplateBinding Content}" 
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                              Margin="{TemplateBinding Padding}" 
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                              />
        </Border>

        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Opacity" Value="0.8" />
            </Trigger>
        </ControlTemplate.Triggers>

    </ControlTemplate>
    <Style x:Key="StyleButtonTemplate" TargetType="{x:Type Button}">
        <Setter Property="Template" Value="{DynamicResource ButtonTemplate}" />
        <Setter Property="FontSize" Value="18pt" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="Button.Effect">
            <Setter.Value>
                <DropShadowEffect Color="Black" Direction="140" ShadowDepth="5" BlurRadius="5" Opacity="0.1" />
            </Setter.Value>
        </Setter>
    </Style>

Upvotes: 1

Views: 1159

Answers (1)

King King
King King

Reputation: 63377

When you re-template a control, all the visual states should be managed by yourself. In this case the disabled state is ignored. For a simple way using Trigger to change the Background if IsEnabled is false:

<ControlTemplate.Triggers>
     <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="Opacity" Value="0.8" />
     </Trigger>
     <Trigger Property="IsEnabled" Value="False">
        <Setter TargetName="border" Property="Background" Value="Gray"/>
     </Trigger>         
</ControlTemplate.Triggers>

Upvotes: 3

Related Questions