Mobile Development at U2U Consult

Based in Brussels, Belgium, U2U Consult has been offering consulting & development services in the EMEA region for over 10 years. We offer mobile development on all platforms from Apple to Android & Microsoft.

Very often the values inside an enumeration type represent a sequence or a ranking, like small-medium-large or good-better-best. In a UI it would be appropriate to represent such a field through a slider control. This article explains how to build such a slider in XAML and C# and how to use it in a MVVM Windows 8 Store app. The slider is implemented as a lightweight user control to allow maximum templatability. The template just comes with a TextBlock that displays the value, and a Slider to change that value. Here’s the template:

The control has two properties, implemented as Dependency Property. Enumeration is the string that contains the fully qualified name of the Enum to which you want to bind, and Value is the property that holds the current enumeration value as a string.

When the Enumeration property is assigned, we populate an internal collection with the enumeration values. The Slider's steps represent the index in that collection, so we reset its maximum to the number of items in the enumeration (minus one). Here’s that process:

Here’s a screenshot of the demo app. The two sliders on it are bound to two different enumerations:

The EnumerationSlider exposes its Value as a string, not as an instance of the linked Enumeration type. So it cannot be bound to a viewmodel’s Enum-type property through a TwoWay Binding. When you move the Slider, an "Error: Cannot save value from target back to source." will be produced. You can solve that problem with a ValueConverter, but then you would need to write one for each enumeration type, and use it in every binding. You could also create a wrapper class for each enumeration that hosts the string-to-value conversion. If you search for ‘BindableEnum’ you’ll find examples of this.

I personally prefer to decorate the viewmodel with a wrapper property of type string that passes the value to the 'real' property, like this:

That code may look cumbersome, but at least it’s in the correct place. The extra property makes the model easily bindable to the view. That’s exactly what a viewmodel is supposed to do. Here’s how to bind viewmodel to the control: