gpt4 book ai didi

c# - 在父构造函数中设置窗口所有者时遇到问题

转载 作者:可可西里 更新时间:2023-11-01 03:07:35 25 4
gpt4 key购买 nike

在 WPF 中,在父级的构造函数中将窗口的 Owner 属性设置为其父级有什么问题吗?应该没有吧?那么,为什么我会从以下代码中得到一个 XamlParseException

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; 也会删除运行时错误。

异常详情:

XamlParseException 未处理

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

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

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

所以我现在正在调查。

最佳答案

问题在于,因为 WPF 仅在第一次显示 WPF 窗口时创建 native 窗口,所以您不能将尚未显示的窗口设置为 Owner(因为这建立了 native 窗口“所有者 -> 拥有”关系,但 native 句柄尚不存在。)

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

关于c# - 在父构造函数中设置窗口所有者时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16550621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com