如何使滑块匹配值

时间:2013-07-18 13:59:56

标签: c# wpf sliders

我目前正在使用WPF中的滑块。我的GUI窗口有两个滑块,它们应该以几种方式一起工作。 slider1必须始终小于或等于slider2slider2必须始终大于或等于slider1。我的previous question中记录了我第一次尝试使用C#代码隐藏来解决此问题。这个问题让我的代码编译,但在运行时没有影响我的程序中的任何视觉变化。使这些滑块以我需要的方式运行的理想方法是什么?

谢谢。

2 个答案:

答案 0 :(得分:2)

假设您的ViewModel有2个属性Slider1Slider2,您的XAML看起来像这样:

<Slider Value="{Binding Path=Slider1}"/>
<Slider Value="{Binding Path=Slider2}"/>

然后,当Slider1Slider2发生更改时,您可以在ViewModel中执行逻辑:

public class MyClass: INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
  {
      var handler = PropertyChanged;
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
  }

  private double _slider1;

  public double Slider1
  {
      get { return _slider1; }
      set
      {
          if (_slider1 != value)
          {
              _slider1 = value;
              OnPropertyChanged("Slider1");
              if (_slider1 > Slider2) Slider2 = _slider1;
          }
      }
  }

  private double _slider2;

  public double Slider2
  {
      get { return _slider2; }
      set
      {
          if (_slider2 != value)
          {
              _slider2 = value;
              OnPropertyChanged("Slider2");
              if (_slider2 < Slider1) Slider1 = _slider2;
          }
      }
  }
}

答案 1 :(得分:1)

为了您的轻松,您也可以这样做..

 private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        if (slider1 == null || slider2 == null)
            return;
        if (slider1.Value >= slider2.Value)
        {
            slider2.Value = slider1.Value;
        }



    }

    private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        if (slider1 == null || slider2 == null)
            return;
        if (slider2.Value <= slider1.Value)
        {
            slider1.Value = slider2.Value;
        }


    }