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

时间:2012-09-25 07:49:55

标签: wpf xaml dependency-properties observablecollection design-time

好的,我厌倦了这个问题。

我正在尝试创建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,就像我可以使用元素集合填充的本机控件一样?我想在第二天找到答案。

1 个答案:

答案 0 :(得分:8)

我经常检查一下我是否在设计时间,然后再联系事件等。

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

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

}

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

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

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

另一方面,我认为你最好使用ItemsControl