如何在ViewModel里设置Textbox聚焦

2025-03-13 14:26:17
推荐回答(1个)
回答1:

首先加一个Behavior,继承Behavior

#region "Using Namespace"

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

#endregion

namespace TestSLApplication
{
public class PasswordboxFocusBehavior : ControlFocusBehaviorBase
{ }

public class TextBoxFocusBehavior : ControlFocusBehaviorBase
{ }

public class ControlFocusBehaviorBase : Behavior
where T : Control
{
public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(ControlFocusBehaviorBase),
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
beh:PasswordboxFocusBehavior.IsFocused="{Binding UsernameValidated}" />