我有一个带有用户名和密码的LoginWindow可以在软件中访问,之后用户通过身份验证我想在下一个窗口中显示(软件的mainWindow)在TextBlock中验证的用户名...我展示了一个我的LoginWindow的代码片段:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public bool ValidateApplicationUser(string userName, string password)
{
{
var AuthContext = new DataClasses1DataContext();
var query = from c in AuthContext.Users
where (c.Username == userName.ToLower() && c.Password == password.ToLower())
select c;
if(query.Count() != 0 )
{
return true;
}
return false;
}
}
private void mahhh(object sender, RoutedEventArgs e)
{
bool authenticated = true;
{
if (usernameTextBox.Text !="" && passwordTextBox.Text != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text , passwordTextBox.Text);
}
}
if (!authenticated)
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Congradulations! You're a valid user!");
MainWindow c = new MainWindow();
c.ShowDialog();
}
}
}
如果我在MainWindow中使用用户名“Marc”进行身份验证,我将在TextBlock中显示用户名“Marc”,我不知道我是否已成功使用? 我怎么能这样做?
答案 0 :(得分:1)
我认为你在代码中有一些错误(它会允许空字段记录),它必须像:
bool authenticated = true;
{
if (usernameTextBox.Text !="" && passwordTextBox.Text != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text , passwordTextBox.Text);
}
}
if (!authenticated || usernameTextBox.Text == "" || passwordTextBox.Text == "")
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Congradulations! You're a valid user!");
MainWindow c = new MainWindow();
c.ShowDialog();
}
答案 1 :(得分:0)
简单地说,将UserName传递给主窗口的构造函数,如下所示
MainWindow c = New MainWindow(usernameTextBox.Text);
在主窗口的构造函数中接收变量中的值并随意执行任何操作,如下所示
private String _userName;
public MainWindow(string userName)
{
_userName = userName
}
答案 2 :(得分:0)
将一个公共变量/属性添加到您的MainWindow类
public string Username { get; set; }
现在你可以设置属性
MessageBox.Show("Congradulations! You're a valid user!");
MainWindow c = new MainWindow();
c.Username = usernameTextBox.Text;
c.ShowDialog();
并在您的MainWindow中使用它
MainWindow_Loaded(..) {
MessageBox.Show("You are " + Username);
}