WPF 用户控件父级 [英] WPF User Control Parent

查看:56
本文介绍了WPF 用户控件父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a user control that I load into a MainWindow at runtime. I cannot get a handle on the containing window from the UserControl.

我试过this.Parent,但它总是为空.有谁知道如何从 WPF 中的用户控件获取包含窗口的句柄?

I have tried this.Parent, but it's always null. Does anyone know how to get a handle to the containing window from a user control in 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 并定位托管您的控件的窗口.

The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

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

You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

这篇关于WPF 用户控件父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆