A nice short post here, I wanted to share with you some code I recently used to create an Apple-style toggle button for WPF applications. I was quite surprised with how easy this was to make. Obviously it isn’t perfect but it makes do for my applications.
This is the style that I used:
<Style TargetType="{x:Type ToggleButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ToggleButton}"> <Viewbox> <Border x:Name="Border" CornerRadius="10" Background="#FFFFFFFF" Width="40" Height="20"> <Border.Effect> <DropShadowEffect ShadowDepth="0.5" Direction="0" Opacity="0.3" /> </Border.Effect> <Ellipse x:Name="Ellipse" Fill="#FFFFFFFF" Stretch="Uniform" Margin="2 1 2 1" Stroke="Gray" StrokeThickness="0.2" HorizontalAlignment="Stretch"> <Ellipse.Effect> <DropShadowEffect BlurRadius="10" ShadowDepth="1" Opacity="0.3" Direction="260" /> </Ellipse.Effect> </Ellipse> </Border> </Viewbox> <ControlTemplate.Triggers> <EventTrigger RoutedEvent="Checked"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="#FF4CD661" Duration="0:0:0.1" /> <ThicknessAnimation Storyboard.TargetName="Ellipse" Storyboard.TargetProperty="Margin" To="20 1 2 1" Duration="0:0:0.1" /> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="Unchecked"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="White" Duration="0:0:0.1" /> <ThicknessAnimation Storyboard.TargetName="Ellipse" Storyboard.TargetProperty="Margin" To="2 1 2 1" Duration="0:0:0.1" /> </Storyboard> </BeginStoryboard> </EventTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
Using this, I am able to have any size toggle button I want and it will still look the same. Thank goodness for view boxes! 🙌
Here is a little GIF showing the toggle button in action. I left it to just resize depending on the actual window to demonstrate it’s scalability:
Enjoy!