[WPF疑难]Hide me! not close
周银辉
有朋友遇到这样的一个问题,在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();
}
//
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);
}
{
e.Cancel = true;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, this.willHide);
}
Everything is OK!
整体的代码:
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);
}
}
}