I recently burnt a little more time than I would have liked making the WPF Slider Control do something simple. Basically, I wanted a slider that would have a minimum value of 0 and a maximum value of 1 with increments of .01.  The Value property of a slider is of type double and when you use the slider it increments/decrements with quite a bit of granularity, to like .0000001 or more.  At first, you'd think setting the SmallChange and LargeChange would fix this, but these properties only affect when the user uses arrow keys or page up/page down keys to change the slider. Direct mouse manipulation doesn't respect these values. So what to do?  Well, you can set the TickFrequency to the value of change you want (in my case .01) and then set the IsSnapToTickEnabled to true. Finally, I set the TickPlacement to "none" because 100 tick marks didn't look so hot. Here's the final XAML:

<Slider
      x:Name="SliderFrom"
      Width="230"
      Height="21"
      TickFrequency=".01"
      IsSnapToTickEnabled="true"
      TickPlacement="none"
      Value="{Binding Path=From, Mode=Default, UpdateSourceTrigger=PropertyChanged}"
      Maximum="1"
      Minimum="0"

/>                          

Oh, and you'll notice that to make any changes on the slider propagate immediately to my data object, I also changed the UpdateSourceTrigger to PropertyChanged.

Posted on December 18, 2008 07:37
Actions: E-mail | Comments (1)

Comments


Marcel

Marcel

December 18, 2008 06:35

If you do want the ticks you can place a TickBar above it.

Fill color in the default slider template is hardcoded and different between XP and Vista so I picked a color somewehere in the middle Smile
You have to enable TickPlacement, set Foreground to Transparent and change the margin to compensate for the now invisible ticks.

And if you want your users to have keyboardnavigation back you should put SmallChange/LargeChange back in.

When I tried to align the tickmarks and the slider using margins, I had some trouble with fuzzy rendering / misalignment of the tickmarks. After a while I noticed the ReservedSpace property (never heard of it before) and this did the trick!

<StackPanel Width="230">
  <TickBar Minimum="0" Maximum="1"
           TickFrequency="0.1"
           Fill="#FFB2B2B2"
           Height="4" ReservedSpace="11"/>
  <Slider x:Name="SliderFrom"
          TickFrequency=".01"
          IsSnapToTickEnabled="true"
          TickPlacement="TopLeft" Foreground="Transparent"
          Value=".5"
          Maximum="1"
          Minimum="0"
          SmallChange="0.01"
          LargeChange="0.1"
          Margin="0,-4,0,0"/>
</StackPanel>

          


Add comment

Enter your name, handle, alias, or email.

We'll incarnate your avatar from the services below.