WPF登录界面记住密码及代码
时间: 2023-10-11 11:11:38 浏览: 252
登陆界面记住密码
WPF登录界面记住密码可以通过设置本地配置文件实现。以下是一份实现代码示例:
在App.xaml.cs中添加以下代码:
```csharp
public static void SaveSetting(string key, string value)
{
Properties.Settings.Default[key] = value;
Properties.Settings.Default.Save();
}
public static string GetSetting(string key)
{
return Properties.Settings.Default[key].ToString();
}
```
在登录窗口的构造函数中添加以下代码:
```csharp
// 读取本地配置文件
if (App.GetSetting("rememberMe") == "true")
{
this.tbUsername.Text = App.GetSetting("username");
this.tbPassword.Password = App.GetSetting("password");
this.chkRememberMe.IsChecked = true;
}
else
{
this.tbUsername.Text = "";
this.tbPassword.Password = "";
this.chkRememberMe.IsChecked = false;
}
```
在登录事件中添加以下代码:
```csharp
// 保存本地配置文件
if (this.chkRememberMe.IsChecked == true)
{
App.SaveSetting("rememberMe", "true");
App.SaveSetting("username", this.tbUsername.Text);
App.SaveSetting("password", this.tbPassword.Password);
}
else
{
App.SaveSetting("rememberMe", "false");
App.SaveSetting("username", "");
App.SaveSetting("password", "");
}
```
在XAML中添加以下代码:
```xaml
<CheckBox x:Name="chkRememberMe" Content="记住密码" Margin="10" IsChecked="{Binding RememberMe, Mode=TwoWay}" />
<TextBox x:Name="tbUsername" Text="{Binding Username, Mode=TwoWay}" Margin="10" />
<PasswordBox x:Name="tbPassword" Password="{Binding Password, Mode=TwoWay}" Margin="10" />
```
其中,ViewModel需要实现INotifyPropertyChanged接口,以便在数据绑定时更新UI。代码示例:
```csharp
public class LoginViewModel : INotifyPropertyChanged
{
private string _username;
public string Username
{
get { return _username; }
set
{
_username = value;
OnPropertyChanged("Username");
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
OnPropertyChanged("Password");
}
}
private bool _rememberMe;
public bool RememberMe
{
get { return _rememberMe; }
set
{
_rememberMe = value;
OnPropertyChanged("RememberMe");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
阅读全文