5

我已经看到了很多样本​​,为了打开关闭的窗口,我应该在关闭事件中隐藏窗口,但是如果我在工作中间关闭窗口并再次打开同一个窗口,它会向我显示我的内容,这对我来说是不公平的离开是因为我之前隐藏了窗口。那么我如何在关闭或隐藏窗口后重新开始我的窗口。

目前我正在调用 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();                    
                }
            }

谢谢,@nagaraju。

4

3 回答 3

11

如果你想要隐藏/显示的行为,你根本不应该在窗口上调用 Window.Close(),而是通过调用 Window.Hide() 来隐藏它。如果用户已经关闭它并且关闭是不可避免的,您可以尝试以下操作。覆盖 Window 内的 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
}

编辑:

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

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

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

此致,

于 2012-01-05T11:30:18.570 回答
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;
   }
}
于 2012-01-05T11:26:52.067 回答
0
 this.Opacity = 0 

“关上窗户”

 this.Opacity = 1 

“重新打开它”

关于 Hide() 方法的说明:在另一个类中,窗口实际上将被视为关闭,并且在使用 ShowDialog() 方法后代码将继续。使用“不透明度”属性可以解决问题。

于 2020-01-08T15:56:13.293 回答