1:附加类实现登陆界面信息绑定
public class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void DoNotify([CallerMemberName] string propName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
public class LoginModel : NotifyBase
{
private string _userName;
public string UserName
{
get { return _userName; }
set
{
_userName = value;
this.DoNotify();
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
this.DoNotify();
}
}
private string _validationCode;
public string ValidationCode
{
get { return _validationCode; }
set
{
_validationCode = value;
this.DoNotify();
}
}
}
密码框特殊处理
public class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));
public static string GetPassword(DependencyObject d)
{
return d.GetValue(PasswordProperty).ToString();
}
public static void SetPassword(DependencyObject d, string value)
{
d.SetValue(PasswordProperty, value);
}
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordHelper), new FrameworkPropertyMetadata(default(bool), new PropertyChangedCallback(OnAttached)));
public static bool GetAttach(DependencyObject d)
{
return (bool)d.GetValue(AttachProperty);
}
public static void SetAttach(DependencyObject d, bool value)
{
d.SetValue(AttachProperty, value);
}
static bool _isUpdating = false;
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PasswordBox password = d as PasswordBox;
password.PasswordChanged -= Password_PasswordChanged;
if (!_isUpdating)
password.Password = e.NewValue?.ToString();
password.PasswordChanged += Password_PasswordChanged;
}
private static void OnAttached(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PasswordBox password = d as PasswordBox;
password.PasswordChanged += Password_PasswordChanged;
}
private static void Password_PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
_isUpdating = true;
SetPassword(passwordBox, passwordBox.Password);
_isUpdating = false;
}
}
界面使用
xmlns:common="clr-namespace:XXX.CourseManagement.Common"
<TextBox Height="42" Text="{Binding LoginModel.UserName,UpdateSourceTrigger=PropertyChanged}"
FontSize="16" Foreground="#555" Template="{StaticResource UserNameTextBoxTemplate}"
Name="txtUserName">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=window}"/>
</TextBox.InputBindings>
</TextBox>
<PasswordBox Grid.Row="1" Height="42" Template="{StaticResource PasswordBoxTemplate}"
FontSize="16" Foreground="#555"
common:PasswordHelper.Attach="True"
common:PasswordHelper.Password="{Binding LoginModel.Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<PasswordBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=window}"/>
</PasswordBox.InputBindings>
</PasswordBox>
<TextBox Grid.Row="2" Height="42" Template="{StaticResource VlidationCodeTextBoxTemplate}"
Text="{Binding LoginModel.ValidationCode,UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=window}"/>
</TextBox.InputBindings>
</TextBox>
具体登陆处理逻辑
public class LoginViewModel : NotifyBase
{
public LoginModel LoginModel { get; set; } = new LoginModel();
public CommandBase CloseWindowCommand { get; set; }
public CommandBase LoginCommand { get; set; }
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; this.DoNotify(); }
}
private Visibility _showProgress = Visibility.Collapsed;
public Visibility ShowProgress
{
get { return _showProgress; }
set
{
_showProgress = value; this.DoNotify();
LoginCommand.RaiseCanExecuteChanged();
}
}
public LoginViewModel()
{
this.CloseWindowCommand = new CommandBase();
this.CloseWindowCommand.DoExecute = new Action<object>((o) =>
{
(o as Window).Close();
});
this.CloseWindowCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });
this.LoginCommand = new CommandBase();
this.LoginCommand.DoExecute = new Action<object>(DoLogin);
this.LoginCommand.DoCanExecute = new Func<object, bool>((o) => { return ShowProgress == Visibility.Collapsed; });
}
private void DoLogin(object o)
{
this.ShowProgress = Visibility.Visible;
this.ErrorMessage = "";
if (string.IsNullOrEmpty(LoginModel.UserName))
{
this.ErrorMessage = "请输入用户名!";
this.ShowProgress = Visibility.Collapsed;
return;
}
if (string.IsNullOrEmpty(LoginModel.Password))
{
this.ErrorMessage = "请输入密码!";
this.ShowProgress = Visibility.Collapsed;
return;
}
if (string.IsNullOrEmpty(LoginModel.ValidationCode))
{
this.ErrorMessage = "请输入验证码!";
this.ShowProgress = Visibility.Collapsed;
return;
}
if (LoginModel.ValidationCode.ToLower() != "etu4")
{
this.ErrorMessage = "验证码输入不正确!";
this.ShowProgress = Visibility.Collapsed;
return;
}
Task.Run(new Action(() =>
{
try
{
var user = LocalDataAccess.GetInstance().CheckUserInfo(LoginModel.UserName, LoginModel.Password);
if (user == null)
{
throw new Exception("登录失败!用户名或密码错误!");
}
GlobalValues.UserInfo = user;
Application.Current.Dispatcher.Invoke(new Action(() =>
{
(o as Window).DialogResult = true;
}));
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
}
finally
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
this.ShowProgress = Visibility.Collapsed;
}));
}
}));
}
}