How to change a WinRT ToggleSwitch color?

K Mehta picture K Mehta · Nov 17, 2012 · Viewed 7.5k times · Source

I'm writing a Windows 8 WinRT app in C#, and would like to dynamically change the color of my ToggleSwitch. I'll be having multiple instances of these, and they won't all have the same color.

I tried to create a custom control that inherits from ToggleSwitch, but I quickly learned that I can't do this because ToggleSwitch is a sealed class. My goal was to add a DependencyProperty of type Brush, and then consume that brush through a TemplateBinding in my custom control's Template.

Is there another way of accomplishing this?

Answer

Mayank picture Mayank · Nov 17, 2012

You will be able to do it in Blend

Right Click on the ToggleSwitch > Edit Template > Edit Copy

Blend will insert lot of XAML in the <Page.Resource>. Changing the Storyboard.TargetName="SwitchCurtain property will change the color of the Curtain.

<VisualState x:Name="PointerOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="SwitchCurtain">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Yellow"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="InnerBorder">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ToggleSwitchTrackPointerOverBackgroundThemeBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="SwitchKnob">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Green"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="SwitchKnob">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Blue"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>