如何在MainWindow中调用静态类内的Dictionary实现文本框验证
解决方法
1. 调整静态类的可访问性
原静态类里的dictionary默认是私有(private),外部无法直接访问。这里提供两种处理方式:
方式一:直接公开字典(简单但封装性弱)
修改静态类,把字典的访问修饰符设为public:
public static class Wachtwoorden { public static readonly Dictionary<string, string> dictionary = new Dictionary<string, string> { {"Tom","1234" }, {"Jan", "8765"}, {"Piet","5678"}, {"Dirk", "4321"} }; }
方式二:添加封装的验证方法(推荐)
这种方式不会暴露内部字典结构,更符合面向对象的封装原则:
public static class Wachtwoorden { static readonly Dictionary<string, string> dictionary = new Dictionary<string, string> { {"Tom","1234" }, {"Jan", "8765"}, {"Piet","5678"}, {"Dirk", "4321"} }; // 公共验证方法,传入用户名和密码返回是否匹配 public static bool CheckCredentials(string username, string password) { return dictionary.TryGetValue(username, out var storedPwd) && storedPwd == password; } }
2. 在MainWindow中调用验证
假设你的MainWindow中有两个文本框txtUsername(用户名输入框)、txtPassword(密码输入框),以及一个触发验证的按钮btnVerify:
对应方式一的调用代码
private void btnVerify_Click(object sender, RoutedEventArgs e) { string inputUser = txtUsername.Text.Trim(); string inputPwd = txtPassword.Text.Trim(); if (Wachtwoorden.dictionary.ContainsKey(inputUser) && Wachtwoorden.dictionary[inputUser] == inputPwd) { MessageBox.Show("验证通过!"); // 这里写验证成功后的逻辑 } else { MessageBox.Show("用户名或密码错误!"); } }
对应方式二的调用代码(更简洁安全)
private void btnVerify_Click(object sender, RoutedEventArgs e) { string inputUser = txtUsername.Text.Trim(); string inputPwd = txtPassword.Text.Trim(); if (Wachtwoorden.CheckCredentials(inputUser, inputPwd)) { MessageBox.Show("验证通过!"); // 这里写验证成功后的逻辑 } else { MessageBox.Show("用户名或密码错误!"); } }
额外提示
- 调用
Trim()是为了过滤用户输入的首尾空格,避免因多余空格导致验证失败 - 如果是WPF项目,要确保按钮的
Click事件已经正确绑定到上述方法
内容的提问来源于stack exchange,提问作者Sheldon Truyens
相关产品推荐
相关产品推荐

