Changing text block foreground color when radio button is checked

MattNorman

Well-known member
Joined
May 22, 2021
Messages
98
Programming Experience
1-3
I have the following style that I am using for my menu:

C#:
    <Style BasedOn="{StaticResource {x:Type ToggleButton}}" TargetType="{x:Type RadioButton}" x:Key="MenuButtonTheme">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="{TemplateBinding Background}">
                        <TextBlock Text="{TemplateBinding Property=Content}" VerticalAlignment="Center" Margin="40,0,0,0"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Focusable" Value="False"/>

        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Background" Value="#101010"/>
            </Trigger>
        </Style.Triggers>
    </Style>

I want to also change the foreground color of the text block when the radio button is checked.

I have tried a few different things including adding control template triggers or adding the property change to the style triggers however neither made any difference.

I can get this working by binding colors from my main view model but seems like a lot of extra properties for something I should hopefully be able to do in the style template.

Appreciate any help that can be offered.
 
Does that current XAML you have there for changing the background currently work? If it does, then changing the foreground should work, but you may have to jump through some hoops to access the correct properties of the TextBlock associated with the radio button.

And yes, you are correct in thinking that there should be a way to just do this all in XAML instead of having to bind to a common property in the ViewModel, specially if it's just meant to be a graphical UI side only effect, and not something functional. I think Josh Smith had a blog post about keeping UI code all in the UI, and if possible all in the XAML.

(On the other hand, if you need to bind the radio button checked state to a property anyway so that your ViewModel and/or Model will get updated, why not just bind to that same property to determine whether the text block should be bold or not? In this case you're not adding an extra property for the sake of just the UI. It's already a property that is being bound for the sake of the Model.)
 
Back
Top Bottom