Having Trouble Setting Window's Owner in Parent's Constructor

吃可爱长大的小学妹 提交于 2019-12-03 11:19:56

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.)

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.

I ended up subscribing to Window.Activated, not Window.StateChanged. Be sure to unsubscribe to it in the handler, as advised in the comments.

    private void OnActivated(object sender, EventArgs eventArgs)
    {
        owned.Owner = this;
        Activated -= OnActivated;
    }

I accepted dlev's answer because it led me directly to finding the answer, even if his didn't work for my exact situation.

You need the WPF equivalent of HandleCreated event, which is SourceInitialized. This should work:

public OwnerWindow()
{
    InitializeComponent();

    SourceInitialized += (s, a) =>
        {
            var owned = new OwnedWindow();
            owned.Owner = this;
        };
}

Note that you don't have to Show either OwnerWindow or OwnedWindow for this to work.

Just adding another option if you need the handle created earlier than normal for some reason, or can't show the window:

new WindowInteropHelper(myWindow).EnsureHandle();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!