Multiple stepped sliders in Xamarin.Forms

Viewed 1117

I have a question about a multiple stepped sliders. I am trying to create multiple stepped sliders, but the problem is that I don't know how to identify which slider value is changed

This is my constructor:

 public FeedbackPage ()
        {
            InitializeComponent ();

            Feedback = new Feedback();

            StepValue = 1.0;

            SliderValueVak.ValueChanged += OnSliderValueChanged;
            SliderValueUitleg.ValueChanged += OnSliderValueChanged;

            this.BindingContext = this;
        }

As you can see if the value of a slider changes, it calls the OnSliderValueChanged method. The code inside this method is shown here below:

void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
        {
            var newStep = Math.Round(e.NewValue / StepValue);

            SliderValueVak.Value = newStep * StepValue;
            SliderValueUitleg.Value = newStep * StepValue;
        }

But now if I use one slider, both slider values change, this is because I give them both the same value. Is there a way to use a if statement or swich case to see which slider value is changed?

2 Answers

sender is the control that fired the event. Simply cast it to the correct type and then you will know which slider was the source

void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
    {
        var newStep = Math.Round(e.NewValue / StepValue);

        var slider = (Slider)sender;
        slider.Value = newStep * StepValue;
    }

As jason said, sender is the control that fired the event.But if you want to do some more .You can define a subclass of Slider

class MySlider:Slider
{
    public readonly int tag;
    public MySlider()
    {

    }

    public MySlider(int tag)
    {
        this.tag = tag;
    }

}

And you can set the tag to distinguish multiple stepped sliders.

SliderValueVak = new MySlider(10);
SliderValueUitleg = new MySlider(20);

Andin the method OnSliderValueChanged

void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
{
   var newStep = Math.Round(e.NewValue / StepValue);

   MySlider slider = (MySlider)sender;

   if(slider.tag==10)// source is SliderValueVak
    {
      SliderValueVak.Value = newStep * StepValue;
      // do some thing more
    }

   else if(slider.tag == 20) //source is SliderValueUitleg
    {
      SliderValueUitleg.Value = newStep * StepValue;
      // do some thing more
    }

  }
Related