Working with WPF and Object Creation

When working with WPF, there is an adjustment with how objects are created that you may not be used to in other environments.  Suppose you have the following window:

<Grid>

<StackPanel>

<WrapPanel Margin="5">

<ComboBox SelectionChanged="Combo_Selected" SelectedIndex="0">..</ComboBox>

<Button Click="Button_Click">Click Me</Button>

</WrapPanel>

</Grid>

This window processes in hierarchial order.  First, the combo box is processed.  Whenever the combo box is instantiated, the SelectionChanged event handler is fired when it sees that the selected index is zero.  In some other contexts, setting the index on load does not raise the event, but in WPF it does.  If your code accesses in the selection changed handler any other element below it, it will be a null reference.

To prevent this, check the IsInitialized property on the form, and if not initialized, exit the method as such:

if (!this.IsInitialized)
    return;

That way, the initial firing of the event, when the window is initialized, is prevented.  This is only needed when accessing other elements.

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.