对于Button的Command的绑定可以通过实现ICommand接口来进行,但是Slider并没有Command属性。
另外如果要实现MVVM模式的话,需要将一些Method和Slider的Event进行绑定,如何进行呢?
(对于UIElement的一些Event进行绑定一定有一些通用的方法,目前还没有深入研究。)
首先,Slider Value的绑定是很简单的, 绑定Slider的Value属性即可。
(1)ViewModel
public class SliderViewModel : ViewModelBase { private string selectedValue; public SliderViewModel() { } public string SelectedValue { get { return this.selectedValue; } set { if (this.selectedValue != value) { this.selectedValue = value; base.OnPropertyChanged("SelectedValue"); } } } }
(2) View, 设定 DataContext 为ViewModel, 绑定SelectValue到 Slider的Value 和TextBlock的Text属性上。
这样当拖动Slider时,Slider的值会传给SelectedValue, 然后SelectValue会传给TexBlock上。
x:Class="WpfApplication2.View.SliderView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vm="clr-namespace:WpfApplication2.ViewModel" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">