Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

Failed Object Initialization

by Jim Jan 13, 2009 1:39 PM

I was getting this nasty error during the parsing of my XAML:

Failed object initialization (ISupportInitialize.EndInit). Value cannot be null.
Parameter name: element  Error at object 'System.Windows.Controls.ComboBox' in markup file. . .

After (too) much digging around I figured that my selection changed event was being invoked during the parsing of the XAML (which seems a little weird.) As part of the logic in this handler, I’m using VisualTreeHelper to find elements in item templates. And VisualTreeHelper apparently does not like being used on half-parsed XAML.

The solution is easy enough; jump out if the XAML isn’t loaded yet.

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!this.IsLoaded)
        return;

And put a check at the top of FindVisualChild to make this easier to debug in the future.

private T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject {
    if (!this.IsLoaded)
        throw new InvalidOperationException("Don't call this during loading, it might fail");

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);

        if (child != null && child is T)
            return (T)child;
        else {
            T childOfChild = FindVisualChild<T>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading