Naveen's Weblog

Bridge to future

Customize a slider in WPF, Step by Step Tutorial

Posted by codingsense on February 1, 2010


Hi,

Today let us explore how to customize a slider control in WPF. I have seen a lot of explanation and looked many articles on net about the slider, but i got the the better idea about it only when I implemented it in my own way.
Let me share the same step by step method with you all.

Download Source (7.8 Kb)

So lets begin, First create a WpfApplication in VS2008 and insert a slider control in the grid layout.Open the designer and click on the XAML view. You will see the below code.

<Grid>
<Slider Name="CusomSlider" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />····
 </Grid>


Now we have to override the Style property of the slider to give it the look we want. We will name the style as MyCustomStyleForSlider and override the style method as below code,

<Slider Name="CusomSlider" Style="{StaticResource MyCustomStyleForSlider}" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />


Slider control is made up of many subcontrols, those include Track which inturn include Track.IncreaseRepeatButton, Track.DecreaseRepeatButton, Track.Thumb.
Thumb is the main sub control that makes the rectangle shape that moves left and right. The same thumb can also be found in horizontal and verticle scrollbars. So lets insert the following default template of all the controls that all together make the slider control.

<Style x:Key="MyCustomStyleForSlider" TargetType="{x:Type Slider}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TickBar x:Name="TopTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Grid.Row="0"/>
<TickBar x:Name="BottomTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Bottom" Height="4" Grid.Row="0"/>
<Border x:Name="TrackBackground"  
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >
<Canvas Margin="-6,-1">
<Rectangle Visibility="Hidden" x:Name="PART_SelectionRange" Height="4.0"
 Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
 Stroke="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"
 StrokeThickness="1.0"/>
</Canvas>
</Border>
<Track x:Name="PART_Track" Grid.Row="1">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.DecreaseLarge}"/>
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.IncreaseLarge}"/>
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb x:Name="Thumb" Background="Black"/>                                        
</Track.Thumb>
</Track>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


Now run the application and check how it looks and works, click on its right and left and a small dot i.e Thumb without any style moves right and left.


Now lets apply style to the thumb and name it as CustomThumbForSlider, below is the implementation.

·<Style x:Key="CustomThumbForSlider" TargetType="{x:Type Thumb}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Ellipse Fill="#FF8F4040" Stroke="#FF000000" Height="15" Width="15"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


and override the above style to the thumb.

<Thumb x:Name="Thumb" Style="{StaticResource CustomThumbForSlider}" Background="Black"/>


After overriding the Thumb style lets have a look of the slider control,

Great, i.e The important thing that makes the slider control is the IncreaseRepeatButton and DecreaseRepeatButton, when clicked on ends they decrease in the size to the amount of the Tickbar value making the other button grow in size and that gives us the illusion that the thumb is moving. Nice move right ok lets get furthur.

Now we need to hide the Increase and decrease repeat buttons so lets create their styles.

<Style x:Key="SliderRepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="Transparent"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


Ok apply the styles to the repeat buttons and run the application, you will see that we have only the thumb that moves left and right on clicking but we dont see any track. So now we shall give border control a proper background and brush so that we get a good look at the starting and ending of the slider control. Lets create a style for both of these properties and apply them to the border.

<SolidColorBrush x:Key="HorizontalSliderTrackNormalBackground" Color="#FFE7EAEA"/>
<LinearGradientBrush x:Key="HorizontalSliderTrackNormalBorder" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFAEB1AF" Offset="0.1"/>
<GradientStop Color="White" Offset=".9"/>
</LinearGradientBrush>
<Border x:Name="TrackBackground" 
 Background="{StaticResource HorizontalSliderTrackNormalBackground}"
 BorderBrush="{StaticResource HorizontalSliderTrackNormalBorder}"                                        
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >


Now run the application, you can see that we have customized the design of our slider control.

Change the ellipse control or the border styles to whatever you desire and you will be able to create your own design for the slider control.
Change some of the properties of tickbar, thumb and repeat buttons and see how they behave, which will give you more hands on with slider controller.

References:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.tickbar.aspx

Happy Learning,
Codingsense 🙂

Advertisements

17 Responses to “Customize a slider in WPF, Step by Step Tutorial”

  1. ts really helpfull and informative , Amazing work darragh ..Way of explanation and pictures presentation is attaractive .

  2. Roshini said

    Hey i am making a slider but I don’t want to use a thumb. Instead the slider should be a transparent box with only a border and the color increase and decrease shuld indicate the inc and decrease in values… ie something like a volume bar where the color indicates the volume increase. How do i do that in blend with wpf!

  3. Joe said

    I have been looking for ages for something like this!!!
    Well done!

  4. very helpful, good work!

  5. JRod said

    Any idea what I need to change to make this work for a vertical slider?

    • codingsense said

      Hi JRod,

      Sorry for the delay, the procedure given is for slider that includes both horizontal and vertical the same steps you can use to modify the behavior of vertical slider too.

  6. Nikhil said

    thanks just what i wanted .Great work.

  7. Vijay said

    Nice article. but it is not useful for me.

  8. Adrian J said

    Thank you, very helpful.
    The entry for the bottom tickbar should be corrected for the grid row from

    to

  9. srinivas said

    str output: 290Electric Power100031Gasoline (Petrol)100034Green Power291Natural Gas100092Wastewater – Surface
    Dim strOutput As String = reader.ReadToEnd()

    how to bind this to gridview plz help me

  10. anwar jamal said

    After changing the Orientation of the slider to “Vertical”, It does not change

  11. SuperMiha said

    Thank you, very helpful.

  12. João said

    Thanks!
    For those of you who want the orientation vertical and it does not change properly, if you don’t want to change the style properties you can just change the orientation of the slider 90º or 270º like:

  13. shafeeq aslam said

    thank you
    Slider is verygood
    I like it

  14. Artiom said

    Thank you. Helped me

  15. Arash said

    Good job man! Very helpful.

  16. petrov said

    Thank you so much, this is lifesaver 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s