您不需要为此使用线程。将登录窗口作为对话窗口打开。然后根据登录状态,您可以在单击登录按钮时打开下一个窗口。
请找到以下示例并根据您的要求进行必要的更改。我将在后面的代码中显示这一点,如果需要,您可以为 MVVM 更改它。
在 App.xaml.cs 中
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
LoginWindow lw = new LoginWindow();
bool? rslt = lw.ShowDialog();
if (rslt == true)
{
MainWindow mw = new MainWindow();
mw.Show();
}
else
this.Shutdown();
}
还将 ShutdownMode="OnExplicitShutdown" 添加到 App.xaml
<Application x:Class="YourApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShutdownMode="OnExplicitShutdown">
<Application.Resources>
</Application.Resources>
在您的登录窗口中根据需要添加按钮和文本框
<Window x:Class="YourApp.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="LoginWindow" Height="300" Width="300">
<Grid>
<Button x:Name="ButtonLogin" Content="Login" HorizontalAlignment="Left" Height="21" Margin="95,192,0,0" VerticalAlignment="Top" Width="66" RenderTransformOrigin="1.485,0.81" Click="ButtonLogin_Click"/>
<Button x:Name="ButtonClose" Content="Close" HorizontalAlignment="Left" Height="21" Margin="95,192,0,0" VerticalAlignment="Top" Width="66" RenderTransformOrigin="1.485,0.81" Click="ButtonClose_Click"/>
</Grid>
</Window>
现在在 LoginWindow.xaml.cs 后面的代码中
public partial class LoginWindow : Window
{
public LoginWindow()
{
InitializeComponent();
}
private void ButtonLogin_Click(object sender, RoutedEventArgs e)
{
//code here for checking login status
//.........
if(loginSuccess)
{
DialogResult = true;
}
else
{
DialogResult = false;
}
Close();
}
private void ButtonClose_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
}
然后在 MainWindow.xaml.cs 中连接到 Explicit Shout down
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closed += MainWindow_Closed;
}
void MainWindow_Closed(object sender, EventArgs e)
{
App.Current.Shutdown();
}
}