好吧我对这个问题感到厌恶。WPF设计时间错误对象引用未设置为对象的实例
我想让UserControl在那里我可以从XAML填充它的内容。以前我创建了ObservableCollection DependencyProperty。它在运行时工作,但在设计时出现错误:
未将对象引用设置为对象的实例。
现在我做了简单的版本:
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; }
}
}
这是我愿意用我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>
但是它仍然给了我在设计时的错误:
对象引用不对设置为一个对象的实例。
所以,如果任何人都可以帮助我。
如何使UserControl可以像本机控件一样使用,我可以使用元素的集合来填充该控件?我正在尝试第二天找到答案。
你尝试调用'的InitializeComponent()是更好的,你应该这样做..
在另一方面, “首先? – Ofiris