#1,024 – Making a Slider Cycle through Values of an Enumerated Type
March 7, 2014 Leave a comment
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;