WPF design time error Object reference not set to an instance of an object

Michał Jankowski picture Michał Jankowski · Sep 25, 2012 · Viewed 9.6k times · Source

Ok I am getting sick of this problem.

I am trying to make UserControl where I can populate its content from XAML. Previously I have created ObservableCollection DependencyProperty. It was working at runtime but at design time there was an error:

Object reference not set to an instance of an object.

Now I did simpler version:

public partial class UC : UserControl
{
    public UC()
    {
        Labels = new ObservableCollection<Label>();
        InitializeComponent();

        Labels.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Labels_CollectionChanged);
    }

    void Labels_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        foreach (Label uc in e.NewItems)
            Container.Children.Add(uc);
    }

    private ObservableCollection<Label> _lables = new ObservableCollection<Label>();

    public ObservableCollection<Label> Labels
    {
        get { return _lables; }
        set { _lables = value; }
    }
}

This is how I like to use my UserControll

<Window x:Class="WpfApplication1.MainWindow"
    xmlns:gsh="clr-namespace:WpfApplication1"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid Margin="0,0,0,30">
    <gsh:UC x:Name="uC1">
        <gsh:UC.Labels>
            <Label Content="qwerty1" />
            <Label Content="qwerty2" />
        </gsh:UC.Labels>
    </gsh:UC>
</Grid>

However it still gives me the error at design time:

Object reference not set to an instance of an object.

So if anyone can help me please.

How can I make UserControl that I can use like native controls which I can populate with collection of elements? I am trying to find the answer second day already.

Answer

Richard Friend picture Richard Friend · Sep 25, 2012

I usually check to see if i am in design time before wiring up events etc..

It could be that your Container is null in design mode.

public class Utils
{
    public static bool IsInDesignerMode
    {
        get
        {
            return ((bool)(DesignerProperties.IsInDesignModeProperty
                .GetMetadata(typeof(DependencyObject)).DefaultValue));
        }
    }

}

Maybe in your constructor you should do this..

public UC()    
{    
    InitializeComponent();    
    if (!Utils.IsInDesignerMode)
    {
        Labels = new ObservableCollection<Label>();    

        Labels.CollectionChanged += new         System.Collections.Specialized.NotifyCollectionChangedEventHandler(Labels_CollectionChanged);    
    }
}  

On another note though i think you would be better using an ItemsControl