电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

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


发布日期:2021/2/11
 

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

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

假设我们的Window类型的win时一个需要隐藏的窗口企图关闭该窗体时其会被隐藏点击主窗口上的btnShowWin按钮时窗体会再次被显示

我们实现一个Delegate其代理的方法将异常窗体

delegate void WillHide();

//

private WillHide willHide;

//

thiswillHide = new WillHide(thisHideWin);

//

private void HideWin()

{

thiswinHide();

}

当Closing时我们这样

void win_Closing(object sender CancelEventArgs e)

{

eCancel = true;

DispatcherBeginInvoke(SystemWindowsThreadingDispatcherPriorityNormal thiswillHide);

}Everything is OK!

整体的代码

Code

using System;

using SystemCollectionsGeneric;

using SystemLinq;

using SystemText;

using SystemWindows;

using SystemWindowsControls;

using SystemWindowsData;

using SystemWindowsDocuments;

using SystemWindowsInput;

using SystemWindowsMedia;

using SystemWindowsMediaImaging;

using SystemWindowsNavigation;

using SystemWindowsShapes;

using SystemComponentModel;

namespace ClosingDemo

{

/**//// <summary>

/// Interaction logic for Windowxaml

/// </summary>

public partial class Window : Window

{

delegate void WillHide();

private Window win = new Window();

private WillHide willHide;

public Window()

{

InitializeComponent();

Test();

}

private void HideWin()

{

thiswinHide();

}

private void Test()

{

AppCurrentMainWindow = this;

AppCurrentShutdownMode = ShutdownModeOnMainWindowClose;

thiswillHide = new WillHide(thisHideWin);

thiswinClosing += new CancelEventHandler(win_Closing);

thisbtnShowWinClick += new RoutedEventHandler(btnShowWin_Click);

thiswinShow();

}

void btnShowWin_Click(object sender RoutedEventArgs e)

{

thiswinShow();

}

void win_Closing(object sender CancelEventArgs e)

{

eCancel = true;

DispatcherBeginInvoke(SystemWindowsThreadingDispatcherPriorityNormal thiswillHide);

}

}

}

上一篇:如何编写随Windows启动运行的程序

下一篇:VS在Debug时检测到Loaderlock的解决办法