Sunday, March 16, 2014

#1,024 – Making a Slider Cycle through Values of an Enumerated Type

Inline image 1

You may want to use a Slider control to let a user select from a set of values specified by an enumerated type.  For example, you could let users select a day of the week from the DayOfWeek enumerated type.
Here's one way to do that.  In XAML, define Slider and TextBlock that uses a value converter to display the day.

<Window.Resources>
    <local:DayOfWeekEnumToStringValueConverter x:Key="dayOfWeekEnumToStringConverter"/>
</Window.Resources>
 
<StackPanel>
    <Slider Name="mySlider" Margin="10"
            Minimum="0"
            IsSnapToTickEnabled="True"/>
 
    <TextBlock Text="{Binding Path=Value, ElementName=mySlider, Converter={StaticResource dayOfWeekEnumToStringConverter}}"
                Margin="10"/>
</StackPanel>

public class DayOfWeekEnumToStringValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DayOfWeek day = (DayOfWeek)((double)value);
        return day.ToString();
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}