user310291
user310291

Reputation: 38190

Why Silverlight slider ValueChanged is triggered multiple times whereas It is clicked only once?

I did put a counter to be sure and indeed it increments multiple times whereas there was just one click on slider (no drag at all) why ?

namespace testslider
{
    public partial class MainPage : UserControl
    {
        private int counter = 0;

        public MainPage()
        {
            InitializeComponent();
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            counter = counter + 1;
        }
    }
}

Upvotes: 1

Views: 1414

Answers (3)

bendewey
bendewey

Reputation: 40235

This is likely because the Template for a Slider is made up of a Thumb, and a left and right side RepeatButton.

Represents a control that raises its Click event repeatedly from the time it is pressed until it is released.

If you don't want this functionality you should modify the template and change them from RepeatButtons to just regular Buttons. Let me know if you need a sample.

If you don't have Expression Blend, this page may help you learn what components make up the Slider. http://msdn.microsoft.com/en-us/library/ms753256.aspx (note: this is WPF, but the Silverlight version is similar)

Upvotes: 0

Rick Sladkey
Rick Sladkey

Reputation: 34240

I tried to repeat your experiment and got different results. With this markup:

<Grid>
    <StackPanel>
        <Slider Minimum="1" Maximum="10" Value="5" ValueChanged="Slider_ValueChanged"/>
    </StackPanel>
</Grid>

and this code-behind:

    private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        Debug.WriteLine("ValueChanged: {0} => {1}", e.OldValue, e.NewValue);
    }

I got this debug output:

ValueChanged: 0 => 1
ValueChanged: 1 => 5

without clicking at all and clicking without dragging produces no additional ValueChanged events. So I do see two ValueChanged events but they occur during startup, not during clicking. The first event is the value being coerced to lie within the valid range and the second event is the local value specified in the XAML.

Upvotes: 0

as-cii
as-cii

Reputation: 13019

First of all I think this is not a programming question and if it is I haven't maybe understood it well.

Anyway, think about the slider behaviour: the value can be changed by clicking multiple times in the slider line or just by dragging the slider button to left/right.

So if the user, or you in this case, clicks the button and then drags it to the desired position you will have only one click but multiple ValueChanged events caused by the dragging.

Upvotes: 1

Related Questions