How to close parent windows using WPF User Control
如何使用 WPF 用戶控件關(guān)閉父窗口
【問題描述】
假設(shè)有兩個WPF窗口:window1和window2。
window1有一個按鈕,單擊此按鈕將打開window2。window2包含一個用戶控件。此用戶控件有一個用于關(guān)閉window2的按鈕。
怎樣才能實現(xiàn)這個場景呢?
【解決方案1】
在創(chuàng)建的自定義控件中,從按鈕事件單擊中訪問父窗口。
簡單地說:
var myWindow = Window.GetWindow(this);
myWindow.Close();
或者使用可視化樹:
var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a=>a is Window);
myWindow.Close();
當然,另一種時創(chuàng)建一個顯示”MyButtonClicked“的自定義事件,然后讓承載UserControl的窗口監(jiān)聽此事件,并在觸發(fā)事件時關(guān)閉當前窗口。
[解決方案2]? (討論 )
實現(xiàn)此功能時為了在window2打開時關(guān)閉window1,但如果你將這些代碼放在相應(yīng)的區(qū)域中,它應(yīng)該可以在任何情況下從任何地方關(guān)閉任何窗口:
創(chuàng)建一個存儲Window對象的類,以及一個將關(guān)閉它的函數(shù):
CloseWindow.cs
public static class CloseWindow{
public static Window WinObject;
public static void CloseParent(){
try{
((Window)WinObjcet).Close();
}catch(Exception ex)
{
string value = e.Message.ToString();? //do whatever with this
}
}
}
在父窗口(您要關(guān)閉的窗口-window2,在這種情況?)中,在其onload事件中,將其Window對象設(shè)置為等于CloseWindow.WinObject:
CloseWindow.WinObject = (Window)this;
然后,在孩子的onLoad事件中(或者,在OP的情況下,在Window2的用戶控件的按鈕事件中),讓它執(zhí)行CloseParent()函數(shù):
if(CloseWindow.WinObject != null)
{
CloseWindow.CloseParent();
}
?
【討論】【參考方案3】:
您可以嘗試使用 EventAggregator 在不同的 ViewModel 中實現(xiàn)此事件驅(qū)動邏輯。
http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample
以上是關(guān)于如何使用 WPF 用戶控件關(guān)閉父窗口的主要內(nèi)容,如果未能解決你的問題,請參考以下文章
WPF 用戶控件父級
UserControl在wpf中使用父元素?
C# WPF如何關(guān)閉通過父窗口打開的所有子窗口
如何從作為wpf mvvm模式中的窗口打開的視圖模型中關(guān)閉用戶控件?
如何在WPF中進行模態(tài)對話?文章來源:http://www.zghlxwxcb.cn/news/detail-609647.html
在 WPF 中使用 WebBrowser 關(guān)閉窗口后音頻繼續(xù)播放文章來源地址http://www.zghlxwxcb.cn/news/detail-609647.html
到了這里,關(guān)于如何使用 WPF 用戶控件關(guān)閉父窗口的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!