I was working on our Silverlight4 app today, coding up a child window. I created the child window from a given page, add an event handler for the
Closing
event, and opened the window. I tested in the debugger.
Once I was done in the window, I clicked the OK button. Imagine my surprise when the string I was trying to retrieve was empty. I had tested the window under the debuger, and had already verified that it was setting the string property, but the parent page was getting back an empty string. Enter, the
Debug.WriteLine()
method.
What I found was shocking. It turns out that the OK button handler was indeed being hit, but before the method exited, the window's
Closed
and
Closing
events were firing - BEFORE the OK handler was done with its processing.
The problem was that I had placed the following code at the TOP of the OK click handler:
this.DialogResult = true;
When I moved it to the bottom of the click handler (after all of the processing was done), the events fired in the expected order and at the expected time.
The tip is never make assumptions about how the framework works. I can't recall this being an issue in Windows Forms apps, but it certainly made itself known while I was working in Silverlight.
Be careful out there.
EDIT =============
Changed tags to be more appropriate
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.
My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.