WPF Checkbox style based upon bound value

I have a WPF Checkbox that I wanted to have a different background color based upon a bound value.

So if IsChecked = true I wanted one color and IsChecked = false I wanted a different color.

I noticed that if the Content is filled in then it affects how it functions.

Finally after several attempts I got the following to work (all in XAML):

<CheckBox IsChecked="{Binding CheckBoxBoundProperty, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true, UpdateSourceTrigger=PropertyChanged}" FlowDirection="RightToLeft">
    <CheckBox.Style>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="Content">
                <Setter.Value>
                    <TextBlock Text="Unchecked" />
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content">
                        <Setter.Value>
                            <TextBlock Text="Checked" Background="Gainsboro" />
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

The result functions exactly as I want.

Comments are closed.