【发布时间】:2020-05-07 02:54:04
【问题描述】:
我对 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();。
我第一次登录时,一切正常:主窗口关闭,第二个窗口打开。
但我第二次登录时,第二个窗口打开时主窗口没有关闭。
我花了 3 天的时间试图找到解决方案,而我只是从博客和 Youtube 视频中学习,我无法解决这个问题。
我知道这里有很多类似的问题都有相同的问题,但大多数都涉及 MVVM 中的解决方案。我对所有 MVVM 都不是很熟悉,所以我发现它很难重现。鉴于我的实现,有没有一种简单的方法可以解决这个问题?
【问题讨论】:
-
试试 this.Close();在您要关闭的窗口内
-
问题:根据用户,你显示 HomeWindow 还是 MainWindow,对吗?
-
This.Close() 是我采用的第一种方法,但在方法
AuthentificationAccess中无法识别。不,我只在登录成功时才显示 HomeWindow。如果登录失败,用户将停留在 MainWindow。如果用户退出,他也会回到主窗口(即登录屏幕)。 -
@BrunoBukavuThai:在您拨打
homeWindow.Show()之后立即拨打mainWindow.Close()并删除对Application.Current.MainWindow.Close()的呼叫?