如何在ViewModel里设置Textbox聚焦

 我来答
匿名用户
推荐于2016-01-28
展开全部
首先加一个Behavior,继承Behavior<FrameworkElement>

#region "Using Namespace"

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

#endregion

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);
}

}
}
  然后在ViewModel里面加一个属性UserNameValidated
private bool userNameValited;

public bool UserNameValidated
{
get { return userNameValited;}
set
{
userNameValited = value;
if(notifyPropertyChanged != null)
notifyPropertyChanged("UserNameValidated");
}
}
  在业务逻辑里面用户验证完成且成功了需要设置Textbox聚焦(focus)的时候
UserNameValidated = true;

  在Xaml里面绑定Textbox到这个属性和behavior
<PasswordBox Name="YourBox"
beh:PasswordboxFocusBehavior.IsFocused="{Binding UsernameValidated}" />
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式