Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox changed before Window is loaded

Tags:

c#

.net

wpf

I have a WPF / XAML Window that contains a ComboBox that is giving me problems.

The window's ComboBox is firing off the SelectionChanged event. The Debugger callstack shows me that SelectionChanged is being called (indirectly) from the Window Constructor.

The problem is that the window has an event Window_Loaded, which does some final initialization of data-members. Because this final initialization isn't done yet, the SelectionChanged event fails with a null-reference exception.

There are several ways I could solve this, but I'd like to know the "most correct" way.

  • I could fully initialize all my data members in the constructor. This violates the concept of keeping constructors minimal.

  • I could code the SelectionChanged event handler to properly deal with some data-members being null. This is coding to deal with only a startup problem that will never occur once the Window is fully constructed.

  • I could make the data-members Lazy-Loaded, so they are not initialized by Window_Loaded, but rather when they are first accessed. Seems like a bit of work to solve a problem that could be solved more simply.

I assume I'm not the first person to deal with UI-events prior to the Window Loaded event. What is the preferred way to handle this?

like image 673
abelenky Avatar asked Dec 21 '22 15:12

abelenky


1 Answers

I had a similar problem and while tracing through it I had an "a-ha" moment. I had a default value as "IsSelected", an OnChange event, and a custom loadSettings method. I blamed the settings method at first, but it turned out that having a default value selected triggered the OnChange event before a handful of the controls were loaded, including the parent combobox which was triggering the null reference. Once I removed the "IsSelected" and allowed the default value to be null/empty it worked fine and my loadSettings method took care of setting the default or last used value.

like image 107
Paul Avatar answered Jan 06 '23 05:01

Paul