BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Selection Controls - Slider

The seventy-third part of the Windows Presentation Foundation Fundamentals tutorial looks at the last of the WPF selection controls. This article describes the Slider, which lets users select a value from within a fixed range.

Adding Specific Tick Marks

Regular tick marks are not ideal in all situations. Sometimes you will want to position tick marks individually. You can do so using the Tickmarks property, along with TickPlacement. Tickmarks holds a DoubleCollection, which is a collection of double-precision floating-point numbers. Each value represents the position of a single mark.

You can set the tick mark positions by adding them to the collection programmatically, or in the XAML as a comma-separated list of numbers. We'll use the latter approach to configure the alpha slider. Update the XAML for this control as shown below:

<Slider Name="AlphaSlider"
        Grid.Row="3"
        Orientation="Vertical"
        HorizontalAlignment="Right"
        IsMoveToPointEnabled="True"
        Minimum="0"
        Maximum="255"
        Ticks="0, 128, 192, 224, 240, 255"
        TickPlacement="Both"
        Value="255"
        ValueChanged="SliderChanged"/>

Run the program to see the results. You should see that the tick marks on the vertical slider are positioned according to the collection of values. Note that the thumb is shown as a rectangular block. This is because the TickMarkPlacement is set to Both.

WPF Slider control specific tick marks

Snapping to Tick Marks

As standard, tick marks provide a visual guide to the user only. In some cases you may want it to only be possible to select values at tick marks and not to permit values in-between. This can be achieved by setting the IsSnapToTickEnabled property to true. Once set, dragging the thumb causes it to snap to the nearest tick mark. Changing the value using the keyboard moves to the previous or next marked value.

Let's enable the option for the vertical slider.

<Slider Name="AlphaSlider"
        Grid.Row="3"
        Orientation="Vertical"
        HorizontalAlignment="Right"
        IsMoveToPointEnabled="True"
        Minimum="0"
        Maximum="255"
        Ticks="0, 128, 192, 224, 240, 255"
        TickPlacement="Both"
        IsSnapToTickEnabled = "True"
        Value="255"
        ValueChanged="SliderChanged"/>

Run the program again to see the results.

26 June 2014