How to handle the Slider.ValueChanged event in a view model?

后端 未结 2 1386
感情败类
感情败类 2021-01-07 07:24

I have a PlayerV.xaml View with a Slider inside:


and have a b

相关标签:
2条回答
  • 2021-01-07 07:41

    You have two options. First, despite what you said about not wanting to use code behind, one solution is for you to do just that. In the ValueChanged event handler, you can simply call your view model method when ever the value is changed:

    private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        Slider slider = sender as Slider;
        PlayerVM viewModel = (PlayerVM)DataContext;
        viewModel.YourMethod(slider.Value);
    } 
    

    I've offered this solution because I suspect that you're new to MVVM and still think that you're not allowed to use the code behind. In fact, that is not the case at all and for purely UI matters such as this, it's a good place for it.

    Another option is just to data bind a property directly to the Slider.Value. As the Slider value is changed, so will the property be. Therefore, you can simply call your method from the data bound property setter:

    public double CurrentProgress
    {
        get { return currentProgress; }
        set
        {
            currentProgress = value;
            NotifyPropertyChanged("CurrentProgress");
            YourMethod(value);
        }
    }
    

    One further option involves handling the ValueChanged event in a custom Attached Property. There is a bit more to this solution than the others, so I'd prefer to direct you to some answers that I have already written for other questions, rather than re-writing it all again. Please see my answers to the How to set Focus to a WPF Control using MVVM? and WPF C# - navigate WebBrowser on mouseclick through Binding questions for explanations and code examples of this method.

    0 讨论(0)
  • 2021-01-07 07:51

    By using the event to commend logic you can bind events to your view model, but you need help. You need to use functions from the System.Windows.Interactivity Namespace and include a MVVM Light (there might be other MVVM libraries that have that feature but i use MVVM Light).

    refer this: Is it possible to bind a WPF Event to MVVM ViewModel command?

    0 讨论(0)
提交回复
热议问题