Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to snap to the values on a WPF slider, but only show a tick for some of them

Tags:

wpf

slider

I have a WPF slider whose minimum value = 0 and maximum value = 50. I want to show ticks at an interval of 5, but have the slider snap at an interval of 1. Is this even possible?

like image 597
Kamiikoneko Avatar asked Jan 28 '10 19:01

Kamiikoneko


2 Answers

<Slider TickPlacement="TopLeft" Minimum="0" Maximum="50" TickFrequency="5" IsSnapToTickEnabled="False" SmallChange="1" />

Disable snapping to ticks with IsSnapToTickEnabled="False" and set SmallChange="1".

SmallChange determines the increment when dragging the thumb or pressing the arrow keys. You can also control the increment when the user clicks on the slider (not on the thumb). To make the thumb jump, use LargeChange="10" to jump 10 units. To make the slider move to where the user clicked, use IsMoveToPointEnabled="True". Note, IsMoveToPointEnabled will place the thumb at the nearest SmallChange increment.

like image 63
dobus Avatar answered Sep 19 '22 09:09

dobus


I solved the same issue by displaying only the ticks I wanted by setting the Ticks property, setting IsSnapToTickEnabled to false and using rounding in the binding of the slider value. In my example I want to show slider for 0 to 100%, display ticks in 5% increments and snap step to 1%.

The XAML:

<Slider Minimum="0" Maximum="100"
    TickPlacement="BottomRight" Ticks="{Binding PercentTicks}" 
    TickFrequency="1" SmallChange="1" LargeChange="5"
    Value="{Binding MyProperty, Converter={StaticResource PercentageConverter}}" />

The view model:

    public double MyProperty
    {
        get { return myProperty; }
        set
        {
            myProperty = Math.Round(value, 2);
            OnPropertyChanged();
        }
    }

myProperty has value from 0 to 1, so rounding to 2 digits gives exactly 1% step! Setting the ticks to 5% increments is done in the view model's constructor:

var ticks = new DoubleCollection();
for (int i = 0; i <= 100; i+=5)
{
    ticks.Add(i);
}
PercentTicks = ticks;
like image 37
Velimir Avatar answered Sep 22 '22 09:09

Velimir