实现一个简易的记住密码功能
由于最近一个项目未曾使用数据库,所以在记住密码的时候,只能保存数据到本地,
/// <summary>
/// 保存在本地的登录用户
/// 在不启用数据库的情况下,可以对外使用本地数据
/// </summary>
public class LoginInfoLocation
{
public const string LoginPath = "E://Datas//loginInfo.xml";
}
public class LoginDto
{
public string UserName { get; set; }
public string Password { get; set; }
public bool IsRemember { get; set; }
}
项目使用了Stylet框架
public class LoginViewModel : ViewModelBase
{
private LoginDto _loginDto;
public LoginDto LoginDto
{
get => _loginDto ?? (_loginDto = new LoginDto());
set => SetAndNotify(ref _loginDto, value);
}
private IWriteService _writeService;
private IReadService _readService;
public LoginViewModel(IWriteService writeService,IReadService readService)
{
_writeService = writeService;
_readService = readService;
}
public void ExecuteLogin() { }
public void ExecuteCancel()
{
Application.Current.Shutdown();
}
public void ExecuteChanged()
{
var info = XmlFolderHelper.SerializeXML<LoginDto>(LoginDto);
_writeService.WriteString(LoginInfoLocation.LoginPath, info);
}
protected override void OnActivate()
{
base.OnActivate();
try
{
var xmlData = _readService.Read(LoginInfoLocation.LoginPath);
var doc = XDocument.Parse(xmlData);
List<string> result = doc.Root.Elements().Select(node => node.Value).ToList();
var isRememberValue = doc.Element("LoginDto").Element("IsRemember").Value;
// 将字符串转换为bool类型
if (bool.TryParse(isRememberValue, out bool isRemember))
{
if (isRemember&& result.Count==3)
{
LoginDto = XmlFolderHelper.Deserialize<LoginDto>(xmlData);
}
else
{
LoginDto = null;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}