Home > Software engineering >  How to properly make a controltemplate for a slider in WPF?
How to properly make a controltemplate for a slider in WPF?

Time:09-30

So I've been trying to override the default style for a slider, but I feel like the way I've been doing it is not correct. For one, I'd like to be able to highlight the track behind the thumb. How do I do this the correct way?

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style BasedOn="{StaticResource {x:Type Slider}}"
           TargetType="Slider"
           x:Key="SliderTheme">
        <Style.Setters>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Slider">
                        <Grid>
                            <Border VerticalAlignment="Center"
                                    HorizontalAlignment="Stretch"
                                    Height="5"
                                    Background="White"/>
                            <Track x:Name="PART_Track">
                                <Track.Thumb>
                                    <Thumb x:Name="PART_Thumb">
                                        <Thumb.Template>
                                            <ControlTemplate>
                                                <Border Height="20"
                                                        Width="20"
                                                        Background="#fff"
                                                        CornerRadius="15"/>
                                            </ControlTemplate>
                                        </Thumb.Template>
                                    </Thumb>
                                </Track.Thumb>
                            </Track>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>
</ResourceDictionary>

CodePudding user response:

You can change the track's color like this.

  1. Get the default style by right-clicking the Slider and select Edit template then Edit a copy....
  2. Change the color for <SolidColorBrush x:Key="SliderThumb.Track.Background" Color="HotPink"/>
  • Related