6

好吧我对这个问题感到厌恶。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可以像本机控件一样使用,我可以使用元素的集合来填充该控件?我正在尝试第二天找到答案。

+1

你尝试调用'的InitializeComponent()是更好的,你应该这样做..

public UC() { InitializeComponent(); if (!Utils.IsInDesignerMode) { Labels = new ObservableCollection<Label>(); Labels.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Labels_CollectionChanged); } } 

在另一方面, “首先? – Ofiris

回答

8

我经常检查,看看是否我在设计时连接最多事件等..前

这可能是因为您的容器处于设计模式无效。

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

} 

也许在你的构造,虽然我认为你会使用ItemsControl

+1

哇,很感谢你。你的想法与“IsInDesignerMode”是非常有趣的,但你给我的链接真棒!最后我知道该怎么做。有趣的是,昨天我正在阅读这个页面,经过短暂的阅读,我决定这不是我的问题的答案。显然它是,并再次感谢你的帮助。 –

相关问题