Search code examples
xamlradio-buttontogglebutton

Radiobutton style as toggle button in xaml


I have 2 button which should act as switch, so i use radio button. But the styling of the radio button should look like toggle button, which means, it should not be having a circle to check.

I searched for long time with no helpful resources.

<Style TargetType="{x:Type RadioButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style> 


    <Style TargetType="{x:Type ToggleButton}">
        <Setter Property="Background" Value="{StaticResource BgColor}" />
        <Setter Property="Foreground" Value="{StaticResource FgColor}" />
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="Focusable" Value="False" />
        <Setter Property="Margin" Value="0" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="{StaticResource HoverColor}" />
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="BorderBrush" Value="{StaticResource TextBlack}" />
            </Trigger>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="BorderBrush" Value="{StaticResource TextBlack}" />
                <Setter Property="Foreground" Value="{StaticResource HoverColor}" />
            </Trigger>
        </Style.Triggers>
    </Style>

But it is leaving a space black for circle (radio property) and on mouse Hover, it is showing up the circle to check..

Can anyone know the easiest way to achieve it ..


Solution

  • All you really need to do is define styling for your RadioButtons to look like this:

    <Style TargetType="{x:Type RadioButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <ToggleButton Content="{Binding Path=(Content), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type RadioButton}}}"
                                  IsChecked="{Binding Path=(IsChecked), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type RadioButton}}}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    That's your core. You can add whatever you need to add as another Setters, or style ToggleButton in the ControlTemplate to look like you want it to.