Chetan
Chetan

Reputation: 31

WPF Modal dialog goes in background

I have problem with an application where modal WPF dialog occasionally goes behind the main application window. This hapens when I click button on the dialog which does some processing and updates controls (through binding) in the main application window. When it goes in background - clicking anywhere in the application brings it back into foreground.

        var dialog = LoadDialogWindowThroughMEF();
        dialog.Owner = Application.Current != null ? Application.Current.MainWindow : null;
        dialog.ShowInTaskbar = false;
        dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        return dialog.ShowDialog();

The above code shows how I open modal window. This happens very rarely.

Does anybody know what could be the problem?

Upvotes: 2

Views: 2905

Answers (1)

Christoffer Lette
Christoffer Lette

Reputation: 14806

I'm not sure I have an answer for you, but I can share some of my thoughts:

Every time I've encountered this type of problem, it happened because the Owner wasn't set properly. So, I'd try to not set the Owner and see if that makes the problem reproducible. You need to be absolutely sure that Owner is set to the correct parent window at all times1. You might also want to check that it is the actual MainWindow of your application that are supposed to be the parent. I think that most of the time it is beneficial to be explicit2 in your code. In this case that means that it is better to assign the known parent (maybe you have a reference to the parent somewhere that you could use), rather than relying on the Application.Current to provide you with that reference. Doing so will put you in control of the assignment to Owner. It could even make it possible to get rid of the ?: operator since you would have the means to control the reference even during unit testing.

I also want you to make sure that the code that is actually updating the parent window doesn't in any way force focus to a specific control on the parent window, or anything like that. (As long as the correct parent is set as Owner, I don't see this as a likely problem.)

I hope this helps you, but I understand if it doesn't. The fact that your dialog reappears when you click the parent window disproves some (or all!) of my points...


1 Except when running your unit tests, but that's a completely different matter.

2 As in the first meaning of the word according to wiktionary.org/wiki/explicit, and as opposed to implicit.

Upvotes: 3

Related Questions