在父级的构造函数中有麻烦设置窗口的所有者 [英] Having Trouble Setting Window's Owner in Parent's Constructor

查看:78
本文介绍了在父级的构造函数中有麻烦设置窗口的所有者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,将窗口的Owner属性设置为其父级的构造函数中的父级是否有问题?应该不对吧?那么为什么从下面的代码中得到 XamlParseException

Is there anything wrong in WPF with setting the Owner property of a window to its parent in that parent's constructor? There shouldn't be, right? So why am I getting an XamlParseException from the following code?

public partial class MainView : Window
{
    private readonly OwnedWindow owned;

    public MainView()
    {
        InitializeComponent();
        owned = new OwnedWindow();

        owned.DataContext = DataContext;

        var window = GetWindow(this);
        owned.Owner = this;  //Setting to window causes the same error

        ...
    }

我应该澄清,删除 owned.Owner = this; 也会删除运行时错误。

I should clarify that removing the owned.Owner = this; also removes the runtime error.

异常的详细信息:

XamlParseException未处理


对与指定绑定约束的
匹配的类型'... MainView'的构造方法的调用引发了异常。

The invocation of the constructor on type '...MainView' that matches the specified binding constraints threw an exception.

实际上,我查看了内部异常,它说:

Actually, I looked at the Inner Exception, and it says:


无法将Owner属性设置为

Cannot set Owner property to a Window that has not been shown previously.

所以我现在正在研究它。

So I'm looking into that now.

推荐答案

问题在于,由于WPF仅在第一次显示WPF窗口时才创建本机窗口,因此您无法设置尚未显示的窗口窗口显示为所有者(罪过ce建立本机窗口所有者->拥有关系,但本机句柄尚不存在。)

The problem is that because WPF only creates the native window the first time a WPF Window is shown, you can't be setting a not-yet-shown Window as an Owner (since that establishes a native window "owner -> owned" relationship, but the native handle doesn't yet exist.)

您可以处理所有者窗口上的StateChanged 事件,确保新状态为显示,然后在该位置设置所有者窗口的 Owner 。或者,您可以在那时创建并显示拥有的窗口。

You can handle the StateChanged event on the owner window, ensure that the new state is "shown", and then set the owned window's Owner at that point. Alternatively, you could create and show the owned window at that point.

这篇关于在父级的构造函数中有麻烦设置窗口的所有者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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