Reputation: 3637
I'd like to make a slider like this:
Notice there are little "|" between each slider values, and the user can only select those value.
But I found it is no use to set the SmallChange and LargeChange.
<TextBlock FontSize="44" Text="{Binding ElementName=ColorDarknessStepsSlider, Path=Value}"/>
<Slider x:Name="ColorDarknessStepsSlider" Margin="-12,0" Minimum="3" Maximum="5"
SmallChange="1" LargeChange="1" />
I expect the user could only select 3, 4, 5 but It give me this:
I don't know what's the problem. I am OK with no "|" mark between values, but at least the user must only select the integer value 3, 4, 5. How can I do this?
Upvotes: 3
Views: 2584
Reputation: 192
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
int step = 40;
(sender as Slider).Value = (e.NewValue % step != 0) ? (step - e.NewValue % step) + e.NewValue : e.NewValue;
}
and xaml
<Slider Minimum="400" Maximum="2000" ValueChanged="Slider_ValueChanged"/>
Hope it help;)
Upvotes: 3
Reputation: 1
Try using a converter - that's how I did it.
xaml change is
<Slider x:Name="durationSlider" Margin="-12,0" Minimum="1" Maximum="12"
SmallChange="1" Value="{Binding Settings.Duration, Mode=TwoWay, Converter={StaticResource DoubleToIntConverter}}"/>
public class DoubleToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int rval = (int)value;
if (value != null)
{
return rval;
}
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double val = (double)value;
return (int)val;
}
}
The binded field
private int _duration;
public int Duration
{
get
{
return _duration;
}
set
{
if (value != _duration)
{
_duration = value;
}
// Do this everytime because the initial input is a float converted down to an int
NotifyPropertyChanged("Duration");
}
}
Upvotes: 0
Reputation: 4876
For step length, use Minimum
, Maximum
, SmallChange
For those "ticks", try to play with TickFrequency
and TickPlacement
Upvotes: 0
Reputation: 309
You can do that with xaml [EDIT : Exist only in WPF, appologies] :
<Slider x:Name="ColorDarknessStepsSlider" Margin="-12,0" Minimum="3" Maximum="5"
SmallChange="1" LargeChange="1" TickFrequency="1" />
Or via C# [EDIT : a good way]
private void ColorDarknessStepsSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
double roundedValue = Math.Round(ColorDarknessStepsSlider.Value, 0);
//Check if it is a rounded value
if(ColorDarknessStepsSlider.Value != roundedValue )
ColorDarknessStepsSlider.Value = roundedValue ;
}
Hope it can help ;)
Upvotes: 5