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.
The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With