Search code examples
wpfwpf-controlstogglebutton

Example of Android style toggle button implementation in WPF


<Style x:Key="AndroidToggleBtnStyle" TargetType="ToggleButton">
    <Setter Property="Height" Value="30" />
    <Setter Property="Width" Value="120" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <Border x:Name="outborder"
                        Padding="0"
                        BorderBrush="{StaticResource BorderColorBrush}"
                        BorderThickness="2"
                        CornerRadius="10">
                    <Border x:Name="backgrd"
                            Padding="0"
                            Background="Transparent"
                            CornerRadius="10">
                        <Border x:Name="inercircle"
                                Width="20"
                                Height="20"
                                Margin="5,0,5,0"
                                HorizontalAlignment="Left"
                                Background="{StaticResource BorderColorBrush}"
                                CornerRadius="100">
                            <ContentPresenter />
                        </Border>
                    </Border>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="outborder" Property="BorderBrush" Value="{StaticResource BackColorBlueBrush}" />
                        <Setter TargetName="backgrd" Property="Background" Value="{StaticResource BackColorBlueBrush}" />
                        <Setter TargetName="inercircle" Property="HorizontalAlignment" Value="Right" />
                        <Setter TargetName="inercircle" Property="Background" Value="{StaticResource BackColorWhiteBrush}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

enter image description here

It is defined and used as a style code. When Ischecked, the background color changes. However, there is a slight gap between the outborder and backgrd. How can we fill in the blanks?


Solution

  • You didn't provide StaticResources for the brushes, so I picked ones, but as I understand your question is, how to avoid white gaps between outborder and backgrd Borders

    Old backgrd

    You can fix it by slightly modifying backgrd Border so it'll cover the white gaps but still won't extend over outborder Border.

    <Border x:Name="backgrd"
            Margin="0,-1,0,-1"
            Background="Transparent"
            CornerRadius="8">
    

    New backgrd

    On the example, I intentionally changed outborder BorderBrush to Red to show the difference.