我对C#和WPF感到很陌生,因为我自己学习。
我已经实现了一个登录屏幕,我希望它以一种典型的方式运行:用户输入登录信息(用户名,密码)。如果信息确定,应关闭登录屏幕,然后显示下一个屏幕。这就是我这样做的方式:
该按钮的XAML代码
<Button x:Name="BtnHelloConnect" Content="Connect" Click="BtnHelloConnect_Click" IsDefault="True"/>
点击后,会触发以下代码:
private void BtnHelloConnect_Click(object sender, RoutedEventArgs e)
{
try
{
using (var Connect = new SqlConnection(connstr))
{
Connect.Open();
foreach (ConnectResponse connectResponse in new CheckConnection().CheckIdentity(TextBoxLoginID.Text, PasswprdBoxLoginMDP.Password, ComboBoxLoginInst.Text))
{
if (connectResponse.Reponse == "1")
{
LoggedInData.LoggedInUserId = TextBoxLoginID.Text; //These are some classes that I have created to stored logged-in Data
LoggedInData.LoggedInstitutionId = connectResponse.Entity;
AuthentificationAccess.CheckPrivilege(LoggedInData.LoggedInUserId, LoggedInData.LoggedInstitutionId);
}
else
{
MessageBox.Show(connectResponse.Reponse, "", MessageBoxButton.OK, MessageBoxImage.Stop);
return;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
internal class CheckConnection
{
//Here is the method where I execute a procedure to check whether the user has entered the right loggins. The method return a string "connectResponse"
}
internal class ConnectResponse
{
public string Reponse { get; set; }
public string Entity { get; set; }
}
public static class AuthentificationAccess
{
public static void CheckPrivilege (string username, string entityid)
{
string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
HomeWindow homeWindow = new HomeWindow();
MainWindow mainWindow = new MainWindow();
using (var Connect = new SqlConnection(connstr))
{
Connect.Open();
using (var Command = new SqlCommand("My Procedure", Connect))
{
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("@username", SqlDbType.VarChar).Value = username;
Command.Parameters.Add("@entity_id", SqlDbType.VarChar).Value = entityid;
SqlDataReader dr = Command.ExecuteReader();
while (dr.Read())
{
string UserCategory = dr.GetString(0);
if (UserCategory == "Client")
{
homeWindow.MenuBarProfile.Visibility = Visibility.Collapsed;
}
else
{
MessageBox.Show(UserCategory, "", MessageBoxButton.OK, MessageBoxImage.Stop);
mainWindow.Show();
return;
}
}
Application.Current.MainWindow.Close();
homeWindow.Show();
}
}
}
}
使用Application.Current.MainWindow.Close();
命令执行关闭主窗口(登录窗口)时,我遇到了问题。
第一次登录时,一切正常:主窗口关闭,第二个窗口打开。
但是第二次登录时,第二个窗口打开时mainindow并没有关闭。
我花了3天的时间来寻求解决方案,而我只是从博客和YouTube视频中学习,我一直无法解决。
我知道这里有很多类似的问题,但都涉及相同的问题,但是大多数都涉及MVVM中的解决方案。我对MVVM并不是很熟悉,因此很难复制。根据我的实现,有没有简单的方法来解决这个问题?
答案 0 :(得分:1)
我不认为CheckPrivilege
是打电话给Close
的“正确”地方。相反,我认为您应该将方法更改为:
public static string CheckPrivilege (string username, string entityid)
如果凭据有效,它将返回“用户类别”,否则返回null
。它不会对任何窗口做任何事情。这为您提供了一种不错的static
方法,您可以在应用程序中的任何地方调用它来检查凭据。
关闭登录窗口并打开主窗口以及隐藏/显示各种元素的特定UI逻辑将通过使用该返回值在登录窗口或其他涉及的窗口内部进行处理。这样,您可以通过单击按钮来调用this.Close()
。
答案 1 :(得分:0)
您可以使用一个窗口包含2个不同页面,而不是使用两个窗口。 如果用户已通过身份验证,则可以轻松导航到下一页。