c# - 我们如何将自定义 UserControl 关闭为对话框?

标签 c# wpf .net-4.0

我设计了一个 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/

相关文章:

c# - 如何为面板中的项目添加自定义行为?

c# - 当 ObservableCollection 值更新时,WPF Datagrid 绑定(bind)不更新

c# - 在 ScrollView 中滚动到选定的 Treeviewitem

c# - WCF - 使用 DataMember 装饰 IEnumerable<T> 导致异常 :The underlying connection was closed: The connection was closed unexpectedly

c# - 无法调用类的方法c#

c# - 用于重构安全 ArgumentException 的 Lambda 表达式

.net-4.0 - 微软图表堆积柱形图有差距

c# - 无法在 WPF 项目中加载文件或程序集

c# - 启动画面等待线程完成

c# - 如何运行只有 NotifyIcon 的 "empty"Windows 应用程序?