WPF设计时错误对象引用未设置为对象的实例

Mic*_*ski 6 wpf xaml design-time dependency-properties observablecollection

好吧,我厌倦了这个问题.

我正在尝试创建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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我喜欢使用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>
Run Code Online (Sandbox Code Playgroud)

但是它仍然在设计时给我错误:

你调用的对象是空的.

所以,如果有人能帮助我,请.

我如何制作可以使用的UserControl,就像我可以使用元素集合填充的本机控件一样?我想在第二天找到答案.

Ric*_*end 8

在接线事件等之前,我经常检查我是否在设计时间.

可能是您的Container在设计模式下为null.

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

}
Run Code Online (Sandbox Code Playgroud)

也许在你的构造函数中你应该这样做..

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

        Labels.CollectionChanged += new         System.Collections.Specialized.NotifyCollectionChangedEventHandler(Labels_CollectionChanged);    
    }
}  
Run Code Online (Sandbox Code Playgroud)

另一方面,我认为你会更好地使用ItemsControl