Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle button as Radio button style

I wanted to group a number of toggle buttons and have them behave as radio buttons. So what I did was add radio buttons to my xaml and created the following style:

<Style BasedOn="{StaticResource {x:Type ToggleButton}}" TargetType="RadioButton">
  <Setter Property="FontFamily" Value="Arial"/>
  <Setter Property="FontSize" Value="12"/>
  <Setter Property="Foreground" Value="White"/>
  <Style.Triggers>
    <Trigger Property="IsChecked" Value="True">
      <Setter Property="Background" Value="Red"/>
    </Trigger>
  </Style.Triggers>
</Style>

Now the radio buttons look like toggle buttons, and the font and foreground properties of the style are applied, but if I click on one of the toggle buttons, the background is not changed to red. If I change the foreground based on IsChecked, it works, but I can't get the Background to change when IsChecked is true.

Any ideas?

UPDATE:

It seems that the default ToggleButton style does not use the Background property. I am using the below code now to solve my problem. If anyone sees anything wrong with the below, please let me know.

<DataTemplate x:Key="RedBackground">
      <Grid Background="Red">
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" Text="{Binding}"/>
      </Grid>
    </DataTemplate>

    <Style TargetType="ToggleButton">
      <Style.Triggers>
        <Trigger Property="IsChecked" Value="True">
          <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
          <Setter Property="VerticalContentAlignment" Value="Stretch"/>
          <Setter Property="ContentTemplate" Value="{StaticResource RedBackground}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
like image 511
Flack Avatar asked Sep 17 '10 15:09

Flack


1 Answers

Does the style you are basing on use the Background property at all unless it is set "by user"? That is, can you use the style for toggle button up to this point and explicitly set the background to Red to get the desired effect?

The trigger in the style looks fine, but some styles ignore properties like Background for themed rendering, so setting those properties in a trigger do nothing.

Another possible cause is the notion of dependency property value precedence - when a value is set "locally", the value overrides that given in the style (even if set via a trigger). So if your <RadioButton> tag has a background set, the trigger will do nothing.

like image 172
Philip Rieck Avatar answered Nov 15 '22 07:11

Philip Rieck