如何重新打开关闭的窗口?

nag*_*nag 4 wpf windows-applications

我见过这么多样本,为了打开关闭的窗口,我应该在关闭事件中隐藏窗口,但这对我来说不公平,如果我在工作中间关闭窗口并再次打开同一个窗口它显示我的内容我在哪里离开是因为我之前隐藏了窗户.那么我怎样才能在关闭或隐藏窗口后重新开始我的窗口.

目前我正在调用winload方法,即在调用隐藏窗口的show方法后显示新窗口.

    private PurgeData data=new PurgeData();

private void MenuPurgeData_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                if (PurgeData == null)
                {
                    PurgeData = new PurgeData();
                    PurgeData.Show();
                }
                else
                {
                    PurgeData.WinLoad();
                    PurgeData.Show();                    
                }
            }
Run Code Online (Sandbox Code Playgroud)

谢谢,@ nagaraju.

Dr.*_*ABT 9

如果你想要隐藏/显示的行为,你根本不应该在窗口上调用Window.Close(),而是通过调用Window.Hide()来隐藏它.如果用户关闭了它并且无法避免关闭,您可以尝试以下操作.覆盖窗口内的OnClosing并将e.Cancelled设置为true,然后调用.Hide().即使用户关闭窗口,这也应该允许隐藏/显示窗口.

// Disclaimer, untested! 
protected override void OnClosing(CancelEventArgs e)    
{        
    e.Cancel = true;  // cancels the window close    
    this.Hide();      // Programmatically hides the window
}
Run Code Online (Sandbox Code Playgroud)

编辑:

好的,我现在已经正确地阅读了你的问题;-) 那么我如何在关闭或隐藏窗口后重新开始我的窗口.

当您使用上面的内容重新显示窗口时,它当然将与之前隐藏的窗口相同,因此将具有相同的数据和状态.如果你想要全新的内容,你需要创建一个新的Window()并在其上调用Window.Show().如果您隐藏/显示如上所示,那么您将在隐藏窗口之前将窗口恢复到完全相同的状态.

您是否在WPF应用程序中使用MVVM模式?如果是这样,您可以尝试以下方法.通过将所有数据放在ViewModel中并通过View绑定(即:没有业务逻辑或Window后面的代码中的数据),您可以在ViewModel上调用一个方法,以便在显示窗口时重置所有数据.您的绑定将刷新,窗口状态将被重置.请注意,只有在您正确地遵循MVVM并将主窗体上的所有元素绑定到ViewModel属性(包括子控件)时,这才有效.

最好的祝福,


key*_*rdP 1

这实际上取决于您的应用程序的结构。由于您不维护状态,因此只需保存关闭的窗口的实际类型。根据您使用的窗口类型,您可以为其分配一个 ID(例如在其Tag属性中),以便以后可以识别它。Closing然后,您可以在活动期间将此 ID 推送到Stack. 然后,如果用户重新打开它,则弹出堆栈以获取 ID 并检查对应的窗口。然后您可以重新打开该窗口。

当然,Stack这只是一种数据结构,它可能适合也可能不适合您。使用堆栈意味着用户可以重新打开之前关闭的所有窗口,但也许您可能只需要一个窗口。

编辑-基本代码:

//create an enum to make it easy to recognise the type of window that was open
enum WindowType { Profile, Settings };

//create a stack to hold the list of past windows
Stack<WindowType> pastWindows = new Stack<WindowType>();

//give the window type a particular id 
profileWindow.Tag = WindowType.Profile;

//open the window
profileWindow.Show(); 

//in the closing event, if you want the user to be able to reopen this window, push it to the stack
 protected override void OnClosing(CancelEventArgs e) 
 { 
       pastWindows.Push(WindowType.Profile); //or whatever type it was
       base.OnClosing(e);       
 } 

//to reopen the last window
void ReopenLastWindow()
{
   WindowType lastType = pastWindows.Pop();
   switch(lastType)
   {
      case WindowType.Profile:   
           profileWindow.Show();
           break;
      case WindowType.Settings: 
           settingsWindow.Show();
           break;
      default:
           break;
   }
}
Run Code Online (Sandbox Code Playgroud)