我设计了一个用户控件,并计划在单击主窗口中的按钮时将其显示为弹出窗口。
我点击了这个链接。用于将用户控件作为对话框窗口打开。
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
,然后Close
它。
实现这种目标的一种解决方案可能是以下一种:
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow((DependencyObject)sender);
if (parentWindow != null)
{
parentWindow.Close();
}
}
如您所见,它基于 Window.GetWindow 方法,以下是它的描述:
返回对承载内容树的 Window 对象的引用 依赖项对象所在的位置。
试试
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
这应该有效:-)