[学习记号 - MVVM] 在ViewModel里设置Textbox焦点(focus)

来源:互联网 发布:js input只能输入数字 编辑:程序博客网 时间:2024/05/22 18:15
问题:

设置输入框焦点Textbox.focus()本应该是View的事,为什么要放在ViewModel里设置?

情景假设:

登录模块中,用户输入用户名后,调用WCFRiaService异步验证用户名,如果用户存在,密码输入框自动获得焦点,否则出现指定错误信息。在此情景中,用户验证的业务逻辑应该在ViewModel里面,当业务完成且成功后需要就会涉及到设置Textbox焦点(focus)。

分析:

Textbox没有IsFocused属性,在此种情况下,可按以下思路考虑:首先加一个FocusBehavior,然后把ViewModel的属性UserNameValidated绑定到Textbox,当业务逻辑完成且成功了需要设置Textbox焦点(focus)时,用这个属性通知UI,同时用Behavior自动设置为聚焦(focus)。

 

实现:

1. 加一个Behavior,继承Behavior<FrameworkElement>

using System.Windows;using System.Windows.Controls;using System.Windows.Interactivity;namespace TestSLApplication{    public class PasswordboxFocusBehavior : ControlFocusBehaviorBase<PasswordBox> { }    public class TextBoxFocusBehavior : ControlFocusBehaviorBase<TextBox> { }    public class ControlFocusBehaviorBase<T> : Behavior<FrameworkElement> where T : Control    {        public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(            "IsFocused", typeof(bool), typeof(ControlFocusBehaviorBase<T>),            new PropertyMetadata(IsFocusedPropertyChanged));        private static void IsFocusedPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)        {            var p = dependencyObject as T;            if (p == null) return;            if ((e.NewValue is bool ? (bool)e.NewValue : false))            {                p.Focus();            }        }        public static bool GetIsFocused(T p)        {            return p.GetValue(IsFocusedProperty) is bool ? (bool)p.GetValue(IsFocusedProperty) : false;        }        public static void SetIsFocused(T p, bool value)        {            p.SetValue(IsFocusedProperty, value);        }    }}

2. 在ViewModel里加属性UserNameValidated

private bool userNameValited;public bool UserNameValidated{    get { return userNameValited; }    set    {        userNameValited = value;        if (notifyPropertyChanged != null)            notifyPropertyChanged("UserNameValidated");    }}

3. 业务逻辑里面用户验证完成且成功后,需要设置Textbox聚焦(focus)时

UserNameValidated = true;

4. 在Xaml里面绑定Textbox到这个属性和behavior,至此结束

<PasswordBox Name="YourBox"  beh:PasswordboxFocusBehavior.IsFocused="{Binding UsernameValidated}" />

 

原文参考:http://www.cnblogs.com/mainz/archive/2011/08/25/2153089.html

原创粉丝点击