Andy Bisson
Andy Bisson

Reputation: 580

How to restyle a XAML radio button as a coloured label

I am using the following style with a group of radiobuttons:

       <Style x:Key="RadioTextStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Label Content="{TemplateBinding Content}" Foreground="Red"/>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Background" Value="Green"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

The trigger is not executed and I assume this is because it is looking for the IsChecked property of the Label. How can I properly ensure that the label colour properly tracks the IsChecked state of the underlying RadioButton?

I am still trying many variants of this and currently have the following:

<Style x:Key="RadioTextStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Label x:Name="RadioLabel"  Content="{TemplateBinding Content}" Foreground="Red"/>
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsChecked}" Value="True">
                            <Setter Property="Foreground" Value="Green"/>
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

This looks right to me and intellisense suggests most of the values. However, it still doesn't actually change selected labels to green.

Thanks, Andy

Upvotes: 2

Views: 404

Answers (1)

Chris W.
Chris W.

Reputation: 23290

Keep your original try. You just need to tell your trigger what it's actually changing something on with TargetName like;

<Style x:Key="RadioLabel" TargetType="{x:Type RadioButton}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type RadioButton}">

             <Label x:Name="RadioLabel"
                    Content="{TemplateBinding Content}" Foreground="Red"/>

            <ControlTemplate.Triggers>
               <Trigger Property="IsChecked" Value="True">
                  <Setter TargetName="RadioLabel"
                          Property="Background" Value="Green"/>
               </Trigger>
            </ControlTemplate.Triggers>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

Hope this helps, cheers.

Upvotes: 1

Related Questions