Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF trigger on Content property (bound to boolean) not working

Tags:

binding

wpf

I have a button control that has its Content property bound to a boolean property on my viewmodel. The button is used to open and close a valve on an industrial machine, performed via an asynchronous WCF call. When the service returns it updates the boolean property which in turn triggers a change to the button's visual state. This is the button xaml:

<Button Command="{Binding Path=OpenCloseValveCommand}"
        Content="{Binding Path=ValveIsOpen}"
        Style="{StaticResource ResourceKey=OnOffButtonStyle}">

The button needs to be green when the valve is open, and red with a cross through it when the valve is closed. This is the style xaml:

<Style TargetType="Button" x:Key="OnOffButtonStyle" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Canvas>
                    <Rectangle x:Name="_rect" Fill="Red" Stroke="Black" Width="30" Height="30"></Rectangle>
                    <Path x:Name="_path" Data="M0,0 L30,30 M0,30 L30,0" StrokeThickness="1" Stroke="Black" />
                </Canvas>
                <ControlTemplate.Triggers>
                    <Trigger Property="Content" Value="true">
                        <Setter TargetName="_rect" Property="Fill" Value="Lime" />
                        <Setter TargetName="_path" Property="Visibility" Value="Hidden" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Unfortunately the trigger doesn't seem to fire. I'm guessing it's something to do with the button Content being bound to a boolean type - do I need to use something other than "true" as the trigger value? (The trigger works if I change the viewmodel property to an integer and use 0 or 1, and a trigger Value of "1").

Thanks in advance

Andy

like image 419
Andrew Stephens Avatar asked Dec 20 '25 05:12

Andrew Stephens


1 Answers

You can specify type explicitly:

<Window ...
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        ...>

<Trigger Property="Content">
    <Trigger.Value>
        <sys:Boolean>True</sys:Boolean>
    </Trigger.Value>
    <Setter TargetName="_rect" Property="Fill" Value="Lime" />
    <Setter TargetName="_path" Property="Visibility" Value="Hidden" />
</Trigger>
like image 140
Marat Khasanov Avatar answered Dec 22 '25 20:12

Marat Khasanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!