Discrete Slider in Windows Phone

This morning I found an interesting question on StackOverflow asking how to make the default Windows Phone slider control return discrete values (in this case an integer value rather than the default double).

There are several possible ways to go about this, but the one that leapt out was to create an attached property on the slider and bind to that.

The entire helper class for the property looks like this.

The points to note here are:

  1. On line 7 we hook into the slider’s ValueChanged event so that we can round the value.
  2. Ob line 12 I just return the slider’s Value property, cast as an integer. This value has already been rounded and set on line 7.
  3. If we don’t attach the property, the slider will continue to behave as normal

To use this code in an app, here’s a sample of three sliders, each with a TextBlock to display the Value.

I know this isn’t an elegant solution to the problem, and that it has a couple of issues, but it does work and should give the results the original questioner was after.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">