使用c#在wpf应用程序中使用线程使用第二个窗口时关闭第一个窗口

时间:2015-03-26 05:55:55

标签: c# wpf

我使用c#在Wpf Applicatoin中将MainWindow作为LoginWindow。当我点击Login按钮时它将打开SecondWindow。现在我想使用线程关闭MainWindow。请告诉我这个问题的代码。

1 个答案:

答案 0 :(得分:0)

您不需要使用线程。打开登录窗口作为对话窗口。然后根据登录状态,您可以在单击登录按钮时打开下一个窗口。 请查找以下示例并根据您的要求进行必要的更改。我只是在后面的代码中显示它,如果需要,你可以为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();
    }
}
相关问题