Creating a Slider control that would increment or decrement in powers of 2
How do i make the slider to move only in powers开发者_如何学C of 2
Assuming you are using WPF, create the slider control and a label control using Designer. Double click the slider and it will auto-generate an event handler which is invoked when you move the slider. Inside it, write code as follows:
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
label1.Content = Math.Pow(2, (int)(e.NewValue) ); ;
}
The "e" has the slider value which ranges from 0-10 by default. I'm truncating it to get integers, and then raising 2 with this.
To get more values, multiply e.NewValue, so that your new code looks like this:
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
label1.Content = Math.Pow(2, (int)(e.NewValue*5) ); ;
}
Remember to add limit checks.
Even if you are not using WPF, the idea is similar, and as long as you are using Visual Studio, double clicking the Control creates its default event handler. You can view all the events by checking the properties of the control. Notice that along with the event handler getting created, the slider XAML changes from
<Slider Height="22" Name="slider1" Width="380" />
to
<Slider Height="22" Name="slider1" Width="380" ValueChanged="slider1_ValueChanged" />
You could hide the numbers and use them internally to calculate the power of 2. Display that value next to the slider.
You will have to do this programmatically, I guess handling the ValueChanged event is a starting point.
精彩评论