如何使用 WPF 用户控件关闭父 windows
How to close parent windows using WPF User Control
假设我有两个 WPF windows:window_One 和 window_Two。
- window_One 有一个按钮。单击此按钮打开 window_Two.
- window_Two 包含一个用户控件。
- 此用户控件有一个关闭按钮 window_Two。
我怎样才能实现这个场景?
在您创建的自定义控件中。您可以从按钮事件点击中访问父级 window。
要么通过使用可视化树:
var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a => a is Window);
myWindow.Close();
或简单地:
var myWindow = Window.GetWindow(this);
myWindow.Close();
当然,另一种选择是创建一个自定义事件 "MyButtonClicked",然后让承载 UserControl 的 window 监听此事件,并在触发事件时,你关闭当前 window.
干杯!
您可以尝试使用 EventAggregator 跨不同的 ViewModel 实现此事件驱动逻辑。
http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample
我们实施此操作是为了从打开的 Window2 关闭 Window1,但如果您将这些代码部分放在适当的区域,它应该可以在任何情况下从任何地方关闭任何 window:
创建一个 class 来存储 Window
object,以及一个将关闭它的函数:
CloseWindow.cs
public static class CloseWindow
{
public static Window WinObject;
public static void CloseParent()
{
try
{
((Window)WinObject).Close();
}
catch (Exception e)
{
string value = e.Message.ToString(); // do whatever with this
}
}
}
在parentwindow(window你想关闭-Window2,在这种情况下?),在它的onload事件中,设置它的Window
object 等于 CloseWindow.WinObject
:
CloseWindow.WinObject = (Window)this;
然后,在 child 的 onload 事件中(或者,对于 OP,在 Window2 的用户控件的按钮事件中),让它执行 CloseParent()
函数:
if (CloseWindow.WinObject != null)
CloseWindow.CloseParent();
假设我有两个 WPF windows:window_One 和 window_Two。
- window_One 有一个按钮。单击此按钮打开 window_Two.
- window_Two 包含一个用户控件。
- 此用户控件有一个关闭按钮 window_Two。
我怎样才能实现这个场景?
在您创建的自定义控件中。您可以从按钮事件点击中访问父级 window。
要么通过使用可视化树:
var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a => a is Window);
myWindow.Close();
或简单地:
var myWindow = Window.GetWindow(this);
myWindow.Close();
当然,另一种选择是创建一个自定义事件 "MyButtonClicked",然后让承载 UserControl 的 window 监听此事件,并在触发事件时,你关闭当前 window.
干杯!
您可以尝试使用 EventAggregator 跨不同的 ViewModel 实现此事件驱动逻辑。
http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample
我们实施此操作是为了从打开的 Window2 关闭 Window1,但如果您将这些代码部分放在适当的区域,它应该可以在任何情况下从任何地方关闭任何 window:
创建一个 class 来存储 Window
object,以及一个将关闭它的函数:
CloseWindow.cs
public static class CloseWindow
{
public static Window WinObject;
public static void CloseParent()
{
try
{
((Window)WinObject).Close();
}
catch (Exception e)
{
string value = e.Message.ToString(); // do whatever with this
}
}
}
在parentwindow(window你想关闭-Window2,在这种情况下?),在它的onload事件中,设置它的Window
object 等于 CloseWindow.WinObject
:
CloseWindow.WinObject = (Window)this;
然后,在 child 的 onload 事件中(或者,对于 OP,在 Window2 的用户控件的按钮事件中),让它执行 CloseParent()
函数:
if (CloseWindow.WinObject != null)
CloseWindow.CloseParent();