(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 != )
{
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-- != )
{
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.的更多相关文章
- (WPF, MVVM) Textbox Binding
参考:http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger(v=vs.110).aspx Te ...
- (WPF) MVVM: DataGrid Binding
Binding到DataGrid的时候,需要用到ObservableCollection. public ObservableCollection<Customer> Customers ...
- (WPF) MVVM: ComboBox Binding, XML 序列化
基本思路还是在View的Xmal里面绑定ViewModel的属性,虽然在View的后台代码中也可以实现binding,但是还是在Xmal里面相对的代码量要少一些. 此例子要实现的效果就是将一个List ...
- WPF MVVM实例三
在没给大家讲解wpf mwm示例之前先给大家简单说下MVVM理论知识: WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时 ...
- WPF MVVM 验证
WPF MVVM(Caliburn.Micro) 数据验证 书接前文 前文中仅是WPF验证中的一种,我们暂且称之为View端的验证(因为其验证规是写在Xaml文件中的). 还有一种我们称之为Model ...
- WPF MVVM初体验
首先MVVM设计模式的结构, Views: 由Window/Page/UserControl等构成,通过DataBinding与ViewModels建立关联: ViewModels:由一组命令,可以绑 ...
- [转]WPF/MVVM快速开始手册
I will quickly introduce some topics, then show an example that explains or demonstrates each point. ...
- WPF MVVM实现TreeView
今天有点时间,做个小例子WPF MVVM 实现TreeView 只是一个思路大家可以自由扩展 文章最后给出了源码下载地址 图1 图2 模版加上了一个checkbox,选中父类的checkb ...
- WPF/MVVM 快速开始指南(译)(转)
WPF/MVVM 快速开始指南(译) 本篇文章是Barry Lapthorn创作的,感觉写得很好,翻译一下,做个纪念.由于英文水平实在太烂,所以翻译有错或者译得不好的地方请多指正.另外由于原文是针对W ...
随机推荐
- preventDefault()方法
必须在dragend和dragover事件内调用“事件对象.preventDefault()”方法.因为在默认情况下,拖放的目标元素是不允许接受元素的,为了把元素拖放到其中,必须把默认处理给关掉.目前 ...
- launch文件概述---1
摘要: 原创博客:转载请表明出处:http://www.cnblogs.com/zxouxuewei/ 资源链接:http://wenku.baidu.com/link?url=PhyN3C6ghqo ...
- leetcode 151. Reverse Words in a String --------- java
Given an input string, reverse the string word by word. For example,Given s = "the sky is blue& ...
- kuangbin_ShortPath H (POJ 3660)
本来想自己写个bfs让他顺着胜负边爬 走到拐弯处就判定无法确定次序 然后我发现有多余的边并不会自己省略掉 要写个O(n^3)的删掉多余边这都不如Floyd了 看奚政学长写的是拓扑序也能解 然后在理解看 ...
- (转) Deep Learning in a Nutshell: Reinforcement Learning
Deep Learning in a Nutshell: Reinforcement Learning Share: Posted on September 8, 2016by Tim Dettm ...
- (转) An overview of gradient descent optimization algorithms
An overview of gradient descent optimization algorithms Table of contents: Gradient descent variants ...
- 论文笔记之:From Facial Parts Responses to Face Detection: A Deep Learning Approach
From Facial Parts Responses to Face Detection: A Deep Learning Approach ICCV 2015 从以上两张图就可以感受到本文所提方法 ...
- microsoft Ebook
http://social.technet.microsoft.com/wiki/contents/articles/11608.e-book-gallery-for-microsoft-techno ...
- C#绘图双缓冲
C#绘图双缓冲 C#双缓冲解释: 简单说就是当我们在进行画图操作时,系统并不是直接把内容呈现到屏幕上,而是先在内存中保存,然后一次性把结果输出来,如果没用双缓冲的话,你会发现在画图过程中屏幕会闪的很厉 ...
- createdb test时报global/pg_filenode.map不存在
实际上是存在的,看到说是ipv6占用了5432的端口号,看了一下的确是,将ipv6关闭重启系统即可. 下面是关闭ipv6的方法: 确认IPV6是否开启 在Linux下确认IPv6是否已经被启用,可以从 ...