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

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>

The value converter code could be:

    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();
        }
    }

All that remains is to set the Maximum property. This can be done in code-behind (e.g. in the main window’s constructor):

            mySlider.Maximum = Enum.GetNames(typeof(DayOfWeek)).Length - 1;

1024-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: