您的位置:首页 > 其它

silverlighter下MVVM模式中利用Behavior和TargetedTriggerAction实现文本框的一些特效

2014-05-22 18:18 148 查看
  在silverlight一般开发模式中,给文本框添加一些事件是轻而易举的,然而MVVM开发模式中,想要给文本框添加一些事件并非那么容易,因为MVVM模式中,只有ICommand接口,而且也只有Button中才有Command属性,通过ViewModel可以将方法绑定到Button上面,却无法绑定到文本框和其他一些控件。、

  Behavior的出现解决了这一难题,下面就来说一下具体的实现方法:

  实例一:在用户登录窗口,用户点击Reset按钮后,让用户名输入框自动获取焦点。

  首先要先将ViewModel绑定到我们的控件上面,我们一步一步来做,第一步先写Model,下面是Model的代码:

  

using System;
using System.Net;
using System.Runtime.Serialization;
using System.ComponentModel;

namespace BookModel
{
[DataContract]
public class UserModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private string userName = String.Empty;
private string passWord = String.Empty;

[DataMember]
public string UserName
{
get { return userName; }
set { userName = value; OnPropertyChanged("UserName"); }
}

[DataMember]
public string PassWord
{
get { return passWord; }
set { passWord = value; OnPropertyChanged("PassWord"); }
}

/// <summary>
/// Call the event PropertyChanged.
/// </summary>
/// <param name="PropertyName"></param>
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
}
}


  写完了Model,下一步就是写ViewModel了,在ViewModel中引用Model的命名控件,下面是ViewModel的代码,例子比较简单,就不多解释了。

  

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace BookLibrary
{
public class AutoSetFocusBehavior:Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.TextChanged += OnTextChanged;
}

public void OnTextChanged(object sender, EventArgs e)
{
if(AssociatedObject.Text.Equals(""))
AssociatedObject.Focus();
}
}
}


View Code
  这里前端绑定方法为:

  

<TextBox Text="{Binding user.UserName}" x:Name="txtName" Height="27" HorizontalAlignment="Left" Margin="36,76,0,0" VerticalAlignment="Top" Width="332">
<i:Interaction.Behaviors>
<local:AutoSetFocusBehavior />
</i:Interaction.Behaviors>
</TextBox>


  注意,同样要引入上面的命名空间。

  其实,说了这么多,就是给TextBox加了个OnTextChanged事件,当内容被清空时,判断内容是否为空,为空则设置焦点。

  希望这篇文章能给大家一点帮助。不足之处,还请赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐