[英]How to close a hidden main window in WPF?
我在一個應用程序中有兩個 windows。
第一個 window 有一個按鈕。 當我點擊按鈕時,第二個 window 打開。 (第一個 window 需要關閉或隱藏)。 然后我需要關閉我的第二個 window 並需要停止調試。 怎么做?
<Window x:Class="WpfApp5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp5"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
xmlns:Control="clr-namespace:Syncfusion.Windows.Tools.Controls;assembly=Syncfusion.Tools.Wpf"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Create" Height="50" Width="100" Click="btncreate"></Button>
</Grid>
MainWindow 代碼隱藏:
public partial class MainWindow : Window
{
public static TextBox textBox;
public MainWindow()
{
InitializeComponent();
}
private void btncreate(object sender, RoutedEventArgs e)
{
SecondWindow secondWindow = new SecondWindow();
secondWindow.Owner = this;
this.Hide();
secondWindow.ShowDialog();
}
}
第二個 window:
<Window x:Class="WpfApp5.SecondWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp5"
mc:Ignorable="d"
Title="SecondWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBlock Text="New Project Loaded" HorizontalAlignment="Center" Margin="50"></TextBlock>
</StackPanel>
</Grid>
您的問題似乎是您正在運行顯示 window 的代碼,可能是模態的。 同時,您正在嘗試關閉應用程序。
您尚未顯示此代碼,但如果您的 btnCreate 處理程序之前已關閉
secondWindow.ShowDialog();
您將嘗試在將 window 顯示為對話框的同時有效地關閉應用程序。
您想要的是關閉應用程序的代碼,但不是在 UI 忙於執行其他操作(例如顯示 window)時。
你可以通過移動你的關機來做到這一點,也就是說你正在展示的那個 window 的內容渲染事件處理程序。
另一種選擇是使用調度程序安排關機。
Application.Current.Dispatcher.InvokeAsync(new Action(() =>
{
Application.Current.Shutdown();
}), DispatcherPriority.ContextIdle);
如果您仍然有錯誤,您可以考慮改用。
Environment.Exit(0);
與關閉相比,這是一種相當蠻力的方法,但如果您只是在調試時這樣做,那可能並不重要。
在任何情況下,您都應該確保您沒有顯示另一個 window 或來自任何 windows 的 window.closure 事件的代碼的代碼。 由於關閉應用程序必然涉及關閉 windows。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.