我设计了一个 UserControl 并计划在单击 MainWindow 中的按钮时将其显示为弹出窗口。
我关注了这个Link .用于将用户控件作为对话窗口打开。
private void btnInstApp_Click(object sender, RoutedEventArgs e)
{
Window objWindow = new Window
{
Title = "Title 12345",
WindowStyle = WindowStyle.None,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
AllowsTransparency=true,
Width = 500,
Height = 200,
Content = new ucInstrumentApp()
};
objWindow.ShowDialog();
}
我使用 None
作为 WindowStyle
。并在 UserControl 中设计了一个自定义关闭按钮,用于关闭弹出/对话框窗口。我尝试了下面给出的代码。但它不起作用。
private void btnClose_Click(object sender, RoutedEventArgs e)
{
//this.Close(); //:not working
Window objWindow = new Window
{
Content = new ucInstrumentApp()
};
objWindow.Close();
}
我是 WPF/Windows 窗体的新手。你们能指导我解决这个问题吗。
最佳答案
您需要从当前的 UserControl
获取父级 Window
,然后关闭
它。
实现这种事情的一种解决方案可能是以下一种:
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow((DependencyObject)sender);
if (parentWindow != null)
{
parentWindow.Close();
}
}
如您所见,它基于 Window.GetWindow方法,这是它的描述:
Returns a reference to the Window object that hosts the content tree within which the dependency object is located.
关于c# - 我们如何将自定义 UserControl 关闭为对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811000/