views:

1231

answers:

1

In WPF inside XAML how to extend a ControlTemplate as such that when applied to a button and the button gets disabled it fades to 0.5 opacity while disabled and once enabled fades back to 1.0 opacity.

This visual effect should work also when a parent is being disabled.

+4  A: 

You don't need a ControlTemplate for this. You can accomplish this with just styles. The following button style is applied to all buttons. It sets Opacity to 0.5 when IsEnabled is true and returns it to 1 automatically when the trigger condition doesn't apply anymore. If you're applying the ControlTemplate in a style, you can add this trigger to that one. It also works when the parent is disabled since IsEnabled is inherited.

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Style.Triggers>
            <Trigger Property="Control.IsEnabled" Value="false">
                <Setter Property="Control.Opacity" Value="0.5" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

Or did you specifically require a ControlTemplate solution?

Update

I don't think TemplateBinding supports Converter so if you want to do this in ControlTemplate you need to use something like the following Binding statement high enough in the logical tree.

Opacity={Binding Path=IsEnabled, 
         RelativeSource={RelativeSource TemplatedParent}, 
         Converter={StaticResource BoolToDoubleConverter}}

Where BoolToDoubleConverter is a IValueConverter which returns 1 for true and 0.5 for false. I'd still recommend the style approach if you can use styles. Much simpler I believe.

Mikko Rantanen
Thanks, works fine just as a style trigger.
zproxy