WPF中Closing窗体时调用Hide()方法异常

文/不详  出处/中国IT实验室

有朋友遇到这样的一个问题,在WPF中,当Closing一个窗体时,将e.Cancel=true,然后再调用Hide()方法,以便隐藏窗口而不是关闭,但报异常了:“当Window Closing时不能设置Visibility,或调用Show(),Close(),Hide()方法”。OK,本随笔将帮你解决该问题。

  问题的关键在于不能再Closing方法中调用Close等,那么只要我们知道用户有意图关闭窗体时,仅仅再Closing方法中取消关闭,然后在Closing紧接着的某个方法中调用Hide就OK了。为了体现这个“紧接着的某个方法”,让我联想到方法排队,比如多个线程中的方法使用同一个对象时,这些方法将被排队,否则异常。那么就用Invoke来帮我们实现这个排队就OK了。

  假设我们的Window类型的win2时一个需要隐藏的窗口,企图关闭该窗体时其会被隐藏,点击主窗口上的btnShowWin2按钮时窗体会再次被显示。
  我们实现一个Delegate,其代理的方法将隐藏窗体:
  delegate void WillHide();
  //
  private WillHide willHide;
  //
  this.willHide = new WillHide(this.HideWin2);
  //
  private void HideWin2()
  {
  this.win2.Hide();
  }
  当Closing时我们这样:
  void win2_Closing(object sender, CancelEventArgs e)
  {
  e.Cancel = true;
  Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, this.willHide);
  }Everything is OK!

  整体的代码:
  Code
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Data;
  using System.Windows.Documents;
  using System.Windows.Input;
  using System.Windows.Media;
  using System.Windows.Media.Imaging;
  using System.Windows.Navigation;
  using System.Windows.Shapes;
  using System.ComponentModel;

  namespace ClosingDemo
  {
  /**//// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
  delegate void WillHide();

  private Window2 win2 = new Window2();
  private WillHide willHide;

  public Window1()
  {
  InitializeComponent();

  Test();
  }

  private void HideWin2()
  {
  this.win2.Hide();
  }


  private void Test()
  {
  App.Current.MainWindow = this;
  App.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

  this.willHide = new WillHide(this.HideWin2);

  this.win2.Closing += new CancelEventHandler(win2_Closing);

  this.btnShowWin2.Click += new RoutedEventHandler(btnShowWin2_Click);


  this.win2.Show();

  }

  void btnShowWin2_Click(object sender, RoutedEventArgs e)
  {
  this.win2.Show();
  }

  void win2_Closing(object sender, CancelEventArgs e)
  {
  e.Cancel = true;
  Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, this.willHide);
  }

  }
  }

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [WPF] 的这些文章也感兴趣:

[Prism]Composite Application Guidance for WPF(7)——模块
[Prism]Composite Application Guidance for WPF(9)——命令
用WPF实现在ListView中的鼠标悬停Tooltip显示
[Prism]Composite Application Guidance for WPF(3)
WPF学习之使用DataGrid
WPF实现的又一个阅读器——MSDN Reader
[Prism]Composite Application Guidance for WPF(1)--概览
WPF 常见问题解答
[Prism]Composite Application Guidance for WPF(5)——依赖注入容器
WPF中对ListView排序