c# - WPF 用户控件父级

标签 c# .net wpf

我有一个在运行时加载到 MainWindow 中的用户控件。我无法从 UserControl 获取包含窗口的句柄。

我已经尝试过 this.Parent,但它始终为 null。有谁知道如何从 WPF 中的用户控件获取包含窗口的句柄?

控件的加载方式如下:

private void XMLLogViewer_MenuItem_Click(object sender, RoutedEventArgs e)
{
    MenuItem application = sender as MenuItem;
    string parameter = application.CommandParameter as string;
    string controlName = parameter;
    if (uxPanel.Children.Count == 0)
    {
        System.Runtime.Remoting.ObjectHandle instance = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, controlName);
        UserControl control = instance.Unwrap() as UserControl;
        this.LoadControl(control);
    }
}

private void LoadControl(UserControl control)
{
    if (uxPanel.Children.Count > 0)
    {
        foreach (UIElement ctrl in uxPanel.Children)
        {
            if (ctrl.GetType() != control.GetType())
            {
                this.SetControl(control);
            }
        }
    }
    else
    {
        this.SetControl(control);
    }
}

private void SetControl(UserControl control)
{
    control.Width = uxPanel.Width;
    control.Height = uxPanel.Height;
    uxPanel.Children.Add(control);
}

最佳答案

尝试使用以下内容:

Window parentWindow = Window.GetWindow(userControlReference);

GetWindow 方法将为您遍历 VisualTree 并定位托管您的控件的窗口。

您应该在控件加载后(而不是在 Window 构造函数中)运行此代码,以防止 GetWindow 方法返回 null。例如。连接一个事件:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

关于c# - WPF 用户控件父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/302839/

相关文章:

c# - 在 Silverlight 中向 Intellisense 公开属性

c# - 有没有办法让派生类覆盖 ToString()?

.net - 我应该在 dllimport 中使用 Ansi 还是 Unicode 字符集?

.net - 更新 Excel 工作表 : Cannot update '(expression)' ; field not updateable

c# - 是否可以沙盒化并运行在浏览器的文本字段中输入的 C++ 或 C# 代码?

c# - 使用表达式生成 e => new { e.Id, e.CompanyId }

c# - 依赖属性绑定(bind)未更新

c# - 如何使两个图像与 WPF 重叠?

c# - 自定义DXGrid的 header (DevExpress wpf网格控件)

wpf - 如何在后台线程上执行 WPF 筛选器?