对象引用未设置为Instance WPF Designer

时间:2014-03-24 05:33:12

标签: c# wpf xaml default-constructor

我已经看过以下链接

WPF, 'Object reference not set to an instance of an object' in Designer

我的问题很相似,但有点不同。我没有在XAML中设置任何数据上下文。我正在创建自己的用户控件,我在另一个中使用它。

<usercontrols:MyControl1 x:Name="MyControl1"  Grid.Row="5"  Height="Auto" Width="Auto">

    </usercontrols:MyControl1>

这是我在第二个控件中使用的代码,用于引用MyControl1。这通常不会引发任何异常。但是,当我在MyControl1的构造函数中指定一些代码时,异常就会到来。它还说“无法创建MyControl1的实例”。

1 个答案:

答案 0 :(得分:1)

只需在MainPage.xaml.cs页面中添加此行

即可

使用静态proeprty DesignerProperties.IsInDesignTool确定您的代码当前是否在设计器工具中使用。

InitializeComponent();
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
    //Code that throws the exception
}