我正在用 On_Click 方法创建一个新窗口。首先我试过这个;
public partial class MainWindow : Window
{
CustomerOperations customerOperationsWindow;
public MainWindow()
{
customerOperationsWindow = new CustomerOperations();
InitializeComponent();
}
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
customerOperationsWindow.Owner = this;
customerOperationsWindow.Show();
}
}
它不起作用,所以每次用户单击“客户”按钮时我都开始创建窗口实例。我使用了以下代码。
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
CustomerOperations customerOperationsWindow = new CustomerOperations();
customerOperationsWindow.Owner = this;
customerOperationsWindow.Show();
}
在新窗口中,如果用户点击主按钮,我想导航到主窗口。
private void btnMain_Click(object sender, RoutedEventArgs e)
{
this.Close();
this.Owner.Show();
}
第一个问题:this.Close() 是否释放窗口实例?
第二个问题:这个用法正确吗?
您认为最佳做法是什么?
谢谢大家。
答案 0 :(得分:0)
如果你想切换到父窗口,你可以使用代码this.Owner.Activate();
,如果你想关闭当前窗口,先this.Owner.Activate();
然后this.Close();
。
当您输入 this.Close()
时,编译器到达后不会执行以下几行。当示例窗口仍然存在时,无需重新创建它
private void btnMain_Click(object sender, RoutedEventArgs e)
{
this.Owner.Activate();
this.Close();
}
答案 1 :(得分:0)
Window.Close()
将处理实例分配的所有资源。这就是为什么一旦关闭就无法再次显示它的原因。
如果你想重用同一个 Window
实例,你应该取消关闭过程以防止内部资源的处置并折叠窗口(通过将 Window.Visibility
设置为 Visibility.Collapsed
- { {1}} 也是调用 Visibility.Collapsed
之前实例化的 Window
的默认值)。
或者通过调用 Window.Show()
(将 Window
设置为 Window.Hide()
)而不是 Visibility
来隐藏 Visibility.Hidden
。
调用 Window.Close()
还会将窗口的可见性设置为 Window.Show
。
实际上,通过设置 Visibility.Visible
来显示 Window
是 Window.Visibility
的异步版本。
通常,您可以使用 Window.Activate
方法在 Window 实例之间切换。在当前显示/可见的 Window.Show()
上调用 Window.Show
没有任何作用。
Window
创建 Window 实例会分配非托管资源。如果这种情况经常发生,您将使垃圾收集器保持忙碌。从性能的角度来看,您可能希望避免它并更愿意重用相同的实例。
在常见情况下,这不是必需的。但由于 public partial class MainWindow : Window
{
CustomerOperations CustomerOperationsWindow { get; }
public MainWindow()
{
InitializeComponent();
this.CustomerOperationsWindow = new CustomerOperations();
// Consider to move this logic to CustomerOperations class,
// where you can override the OnClosing method instead of subscribing to the event
this.CustomerOperationsWindow.Closing += CollapseWindow_OnClosing;
}
// Cancel close to prevent disposal and collapse Window instead
private void CollapseWindow_OnClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
this.CustomerOperationsWindow.Visibility = Visibility.Collapsed;
this.CustomerOperationsWindow.Owner.Activate();
}
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
this.CustomerOperationsWindow.Owner = this;
// Calling Show will set the Visibility to Visibility.Visible
this.CustomerOperationsWindow.Show();
}
}
公开了一个 Window
方法,您可以考虑使用它代替 Hide()
。