当前位置:首页 > 网络编程 > 软件语言 > .NET > WPF中Closing窗体时调用Hide()方法异常

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

点击次数:68 次 发布日期:2008-11-06 08:11:27 作者:源代码网
源代码网推荐
广告载入中
有朋友遇到这样的一个问题,在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; 软件开发网 www.mscto.com

源代码网整理以下  namespace ClosingDemo
  {
   /**//// <summary>
   /// Interaction logic for Window1.xaml
   /// </summary>
   public partial class Window1 : Window
   {
   delegate void WillHide();

软件开发网 www.mscto.com

源代码网整理以下   private Window2 win2 = new Window2();
   private WillHide willHide;

源代码网整理以下   public Window1()
   {
   InitializeComponent();

源代码网整理以下   Test();
   } 软件开发网 www.mscto.com

源代码网整理以下   private void HideWin2()
   {
   this.win2.Hide();
   }

源代码网整理以下
   private void Test()
   {
   App.Current.MainWindow = this;
   App.Current.ShutdownMode = ShutdownMode.OnMainWindowClose; 软件开发网 www.mscto.com

源代码网整理以下   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();
   } 软件开发网 www.mscto.com

源代码网整理以下   void win2_Closing(object sender, CancelEventArgs e)
   {
   e.Cancel = true;
   Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, this.willHide);
   }

源代码网整理以下
   }
  }


源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华