(WPF, MVVM) Slider Binding.

对于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">
    <UserControl.DataContext>
        <vm:SliderViewModel />
    </UserControl.DataContext>
    <Grid>
        <Slider HorizontalAlignment="Left"
                Margin="28,102,0,0"
                VerticalAlignment="Top"
                Width="158"
                Minimum="0"
                Maximum="100"
                Value="{Binding SelectedValue}"/>
        <TextBlock HorizontalAlignment="Left"
                   Margin="203,102,0,0"
                   TextWrapping="Wrap"
                   Text="{Binding SelectedValue}"
                   VerticalAlignment="Top" />

    </Grid>
</UserControl>

效果如下:

如果不想显示double值,可以设定Slider的属性。

                TickFrequency="1"
                IsSnapToTickEnabled="True"
                TickPlacement="None" />

其次, 当用鼠标或者键盘移动滑块结束的时候,需要进行一些处理。如果不用MVVM的方式的话,可以在Slider的Event里面增加处理。

用MVVM的话,就稍微麻烦一些。

(1)下载或者复制C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries\System.Windows.Interactivity.dll

在工程中Reference 这个dll,命名空间里面增加:using System.Windows.Interactivity

(2)新写个SliderValueChangedBehavior 继承Behavior<Slider>

    /// <summary>
    /// Helps find the user-selected value of a slider only when the keyboard/mouse gesture has ended.
    /// </summary>
    public class SliderValueChangedBehavior : Behavior<Slider>
    {
        /// <summary>
        /// Keys down.
        /// </summary>
        private int keysDown;

        /// <summary>
        /// Indicate whether to capture the value on latest key up.
        /// </summary>
        private bool applyKeyUpValue;

        #region Dependency property Value

        /// <summary>
        /// DataBindable value.
        /// </summary>
        public double Value
        {
            get { return (double)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
            "Value",
            typeof(double),
            typeof(SliderValueChangedBehavior),
            new PropertyMetadata(default(double), OnValuePropertyChanged));

        #endregion

        #region Dependency property Value

        /// <summary>
        /// DataBindable Command
        /// </summary>
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
            "Command",
            typeof(ICommand),
            typeof(SliderValueChangedBehavior),
            new PropertyMetadata(null));

        #endregion

        /// <summary>
        /// On behavior attached.
        /// </summary>
        protected override void OnAttached()
        {
            this.AssociatedObject.KeyUp += this.OnKeyUp;
            this.AssociatedObject.KeyDown += this.OnKeyDown;
            this.AssociatedObject.ValueChanged += this.OnValueChanged;

            base.OnAttached();
        }

        /// <summary>
        /// On behavior detaching.
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.KeyUp -= this.OnKeyUp;
            this.AssociatedObject.KeyDown -= this.OnKeyDown;
            this.AssociatedObject.ValueChanged -= this.OnValueChanged;
        }

        /// <summary>
        /// On Value dependency property change.
        /// </summary>
        private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var me = (SliderValueChangedBehavior)d;
            if (me.AssociatedObject != null)
                me.Value = (double)e.NewValue;
        }

        /// <summary>
        /// Occurs when the slider‘s value change.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (Mouse.Captured != null)
            {
                this.AssociatedObject.LostMouseCapture += this.OnLostMouseCapture;
            }
            else if (this.keysDown != 0)
            {
                this.applyKeyUpValue = true;
            }
            else
            {
                this.ApplyValue();
            }
        }

        private void OnLostMouseCapture(object sender, MouseEventArgs e)
        {
            this.AssociatedObject.LostMouseCapture -= this.OnLostMouseCapture;
            this.ApplyValue();
        }

        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (this.keysDown-- != 0)
            {
                this.ApplyValue();
            }
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            this.keysDown++;
        }

        /// <summary>
        /// Applies the current value in the Value dependency property and raises the command.
        /// </summary>
        private void ApplyValue()
        {
            this.Value = this.AssociatedObject.Value;

            if (this.Command != null)
                this.Command.Execute(this.Value);
        }
    }

(3) 在View中为Slider的行为添加Command

            <i:Interaction.Behaviors>
                <helper:SliderValueChangedBehavior Command="{Binding ValueChangedCommand}"
                                                  />
            </i:Interaction.Behaviors>

(4)在ViewModel中实现当Slider值个改变的时候进行一些处理。

        public ICommand ValueChangedCommand
        {
            get
            {
                if (this.valueChangedCommmand == null)
                {
                    this.valueChangedCommmand = new RelayCommand(
                        param => this.PopValue(),
                        null);
                }

                return this.valueChangedCommmand;
            }
        }

        private void PopValue()
        {
            MessageBox.Show(String.Format("Selected value is {0}", this.selectedValue));
        }

最后,进行调试,发现ValueChangedCommand当每次Silder值变更的时候都会被执行

那么如何实现最后一次值变更时,才执行Command呢?

(WPF, MVVM) Slider Binding.

时间: 2024-08-06 02:11:39

(WPF, MVVM) Slider Binding.的相关文章

(WPF) MVVM: DataGrid Binding

Binding到DataGrid的时候,需要用到ObservableCollection. public ObservableCollection<Customer> Customers { get { return this.customers; } set { this.customers = value; base.OnPropertyChanged("Customers"); } } (WPF) MVVM: DataGrid Binding,布布扣,bubuko.c

(WPF) MVVM: ComboBox Binding

基本思路还是在View的Xmal里面绑定ViewModel的属性,虽然在View的后台代码中也可以实现binding,但是还是在Xmal里面相对的代码量要少一些. 此例子要实现的效果就是将一个List<Customer> 绑定到一个ComboBox,并将选择后的Customer的Age显示在一个TextBlock中. 1. Model public class Customer { public string Name { get; set; } public int Age { get; s

WPF - MVVM - 如何将ComboBox的Selectchange事件binding到ViewModel

将所有的事件,属性,都映射到ViewModel中.好处多多,以后开发尽量用这种模式. 解决方法: 使用System.Windows.Interactivity.dll,添加该dll到项目引用 ? 1 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" ComboBox映射的代码: <ComboBox VerticalAlignment="Ce

(WPF, MVVM) Event 处理

WPF的有些UI元素有Command属性可以直接实现绑定,如Button 但是很多Event的触发如何绑定到ViewModel中的Command呢? 答案就是使用EventTrigger可以实现. 继续上一篇对Slider的研究,在View中修改Interaction. <i:Interaction.Triggers> <i:EventTrigger EventName="ValueChanged"> <i:InvokeCommandAction Comm

WPF MVVM初体验

首先MVVM设计模式的结构, Views: 由Window/Page/UserControl等构成,通过DataBinding与ViewModels建立关联: ViewModels:由一组命令,可以绑定的属性,操作逻辑构成:因为View与ViewModel进行了解耦,我们可以对ViewModel进行Unit Test: Models:可以是实体对象或者Web服务: 下面通过一个简单的例子,来介绍一些WPF MVVM模式.示例将展示一个图片浏览器,打开图片,放大/缩小图片大小.首先项目结构: UI

转载:WPF MVVM之INotifyPropertyChanged接口的几种实现方式

原文地址:http://www.cnblogs.com/xiwang/ 序言 借助WPF/Sliverlight强大的数据绑定功能,可以比实现比MFC,WinForm更加优雅轻松的数据绑定.但是在使用WPF/Silverlight绑定时,有件事情是很苦恼的:当ViewModel对象放生改变,需要通知UI.我们可以让VM对象实现INotifyPropertyChanged接口,通过事件来通知UI.但问题就出现这里…… 一,描述问题 情形:现在需要将一个Person对象的Name熟悉双向绑定到UI中

WPF MVVM TreeView 实现 右键选中 右键菜单

1.非MVVM模式:下载源代码WpfApplication1.zip <TreeView Height="200" PreviewMouseRightButtonDown="TreeViewItem_PreviewMouseRightButtonDown" HorizontalAlignment="Left" Margin="12,0,0,0" Name="treeView1" VerticalAli

WPF MVVM+EF增删改查 简单示例(二) 1对1 映射

WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. 添加了那些功能,先看看效果图: 第一步:添加实体类StudentPhotoEntity.cs public class StudentPhotoEntity { public int StudentId { get; set; } public byte[] StudentPhoto { get;

A WPF/MVVM Countdown Timer

Introduction This article describes the construction of a countdown timer application written in C# and WPF, using Laurent Bugnion's MVVMLight Toolkit. This article is based on the work of some previous articles I've written: A WPF Short TimeSpan Cus