.net WPF,设计器中的“对象引用未设置为对象的实例”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3533539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF, 'Object reference not set to an instance of an object' in Designer
提问by Sarah Vessels
I'm getting an "Object reference not set to an instance of an object" error when I try to reload the Designer for my XAML UserControl. Visual Studio highlights the following line as being the problem:
当我尝试为我的 XAML 重新加载设计器时,出现“未将对象引用设置为对象的实例”错误UserControl。Visual Studio 将以下行突出显示为问题:
<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
Width="600" TemplateData="{Binding ElementName=cbo_templates,
Path=SelectedItem.Data, Mode=OneWay}"/>
TemplateDetailis another UserControl. When I view TemplateDetail, its Designer view loads just fine, so I don't think there's a problem there. There is a ComboBoxin my XAML named cbo_templatesthat contains instances of my Templateclass, which has a Dataproperty (hence SelectedItem.Data). However, if I remove .Datafrom the Pathin the above XAML, I still get the "Object reference" error, so I don't think the problem is that I'm trying to access the Pathproperty on null. Here's my ComboBoxXAML just in case:
TemplateDetail是另一个UserControl。当我查看时TemplateDetail,它的 Designer 视图加载得很好,所以我认为那里没有问题。ComboBox我的 XAML 中有一个名为的cbo_templates包含我的Template类的实例,它具有一个Data属性(因此SelectedItem.Data)。但是,如果我删除.Data从Path上述XAML,我仍然得到“对象引用”的错误,所以我不认为这个问题是,我想访问Path的属性null。这是我的ComboBoxXAML 以防万一:
<ComboBox ItemsSource="{Binding Path=List}" Grid.Row="1" Grid.Column="3"
VerticalAlignment="Center" x:Name="cbo_templates" Width="250"
HorizontalAlignment="Left" DisplayMemberPath="Name"
SelectedValuePath="Name" SelectedIndex="0"/>
Getting this error is a real problem because the Design view won't load, so I can't see what my UserControllooks like without running the app. Any idea what could be wrong? It builds fine and I don't see any binding problems in the Build Output.
得到这个错误是一个真正的问题,因为设计视图不会加载,所以如果UserControl不运行应用程序,我就看不到我的样子。知道有什么问题吗?它构建得很好,我在构建输出中没有看到任何绑定问题。
Edit:here is the constructor code for both UserControls:
编辑:这是两个UserControls的构造函数代码:
Constructor of UserControlwith "Object reference" error:
UserControl具有“对象引用”错误的构造函数:
InitializeComponent();
grd_templateList.DataContext = this; // refers to containing <Grid> in XAML
Constructor of UserControlI'm trying to embed, the one whose Design view loads okay:
UserControl我正在尝试嵌入的构造函数,其设计视图加载正常:
InitializeComponent();
grd_templateDetail.DataContext = this; // refers to containing <Grid> in XAML
Edit:I tried putting an if (null != grd_templateList)check in the constructors before setting their DataContextproperties, but that didn't help--still getting the "Object reference" error when reloading the Designer.
编辑:我尝试if (null != grd_templateList)在设置它们的DataContext属性之前检查构造函数,但这没有帮助 - 重新加载设计器时仍然出现“对象引用”错误。
Edit:the Listproperty that the ComboBoxuses is a DependencyProperty. I have a default value set in the Registermethod:
编辑:使用的List属性ComboBox是DependencyProperty. 我在Register方法中设置了一个默认值:
public static readonly DependencyProperty ListProperty =
DependencyProperty.Register(
"List",
typeof(List<Template>),
typeof(TemplateList),
new PropertyMetadata(
new List<Template> { _defaultTemplate }
)
);
Even if I try to initialize Listin the constructor for my UserControl, I still get the error when reloading the Designer. I don't think the problem is that Listis null or SelectedItem.Datais a bad path.
即使我尝试List在构造函数中为我的进行初始化,UserControl在重新加载设计器时我仍然会收到错误消息。我不认为问题在于它List是空的或者SelectedItem.Data是一条糟糕的路径。
Edit:okay, even just having this causes my Designer to not load, giving the "Object reference" error:
编辑:好的,即使只是这样也会导致我的设计器无法加载,给出“对象引用”错误:
<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
TemplateData="{Binding}"/>
There is something it dislikes about the TemplateDataproperty being bound, apparently.
TemplateData显然,它不喜欢绑定的属性。
Edit:to add to the mystery, I can view the Design view of my overall/main Window, which includes the UserControlwhose Design view gives me the "Object reference" error. O_o
编辑:为了增加神秘感,我可以查看我的整体/主要的设计视图Window,其中包括UserControl其设计视图给我“对象引用”错误。o_o
回答by NVM
What Alex saysis the way to go. But I think its a little confusing to understand what he is saying.
亚历克斯所说的是要走的路。但我认为理解他在说什么有点令人困惑。
Assuming you have your project open in Visual Studio, open another Visual Studio instance and select Debug->Attach To Process. In the dialog which opens select
假设您在 Visual Studio 中打开了您的项目,打开另一个 Visual Studio 实例并选择Debug->Attach To Process。在打开的对话框中选择
XDesProc.exe(which is the XAML UI Designer) for VS2012 and newerordevenv.exefor older VSversions.
XDesProc.exe(这是 XAML UI 设计器)适用于VS2012 和更新版本或devenv.exe对于较旧的 VS版本。
Then do "Reload Designer" for the user control and see the output in the second VS instance to check what exactly is the error.
然后为用户控件执行“重新加载设计器”并查看第二个 VS 实例中的输出以检查错误究竟是什么。
回答by Lirrik
If you have 'Object reference not set to an instance of an object' in XAML, but your application compiles and runs fine, you will usually find out that its cause is something in a constructor that can't be resolved at design time.
如果您在 XAML 中有“未将对象引用设置为对象的实例”,但您的应用程序编译并运行良好,您通常会发现其原因是在设计时无法解决的构造函数中。
While you can find out the root of the problem with the help of other answers to this question, sometimes that is something you can't simply fix, you need it in your code exactly as you have it, but you don't want to see this error.
虽然您可以在此问题的其他答案的帮助下找出问题的根源,但有时这是您无法简单修复的问题,您需要在代码中完全按照您拥有的方式使用它,但您不想看到这个错误。
In this case, just click the "Disable project code" button located on the bottom of your designer view and Visual Studio designer will stop trying to construct an instance to provide design time data view.
在这种情况下,只需单击位于设计器视图底部的“禁用项目代码”按钮,Visual Studio 设计器将停止尝试构建实例以提供设计时数据视图。
See herefor detailed information.
请参阅此处了解详细信息。
回答by Alex F
If your user control throws exception at design time, you can debug it. To do this, open Dll project with this user control in Visual Studio. Select another Visual Studio instance as executable for debugging. Start debugging. In the second (debugged) Visual Studio instance use your user control in the client XAML page. By this way, you can debug user control in design mode.
如果您的用户控件在设计时抛出异常,您可以对其进行调试。为此,请在 Visual Studio 中使用此用户控件打开 Dll 项目。选择另一个 Visual Studio 实例作为调试的可执行文件。开始调试。在第二个(调试的)Visual Studio 实例中,在客户端 XAML 页面中使用您的用户控件。通过这种方式,您可以在设计模式下调试用户控件。
回答by Chris Persichetti
It's probably something in the constructor of your user controls. VS2008 WPF designer appears have some issues with this.
它可能是您的用户控件的构造函数中的某些内容。VS2008 WPF 设计器似乎对此有一些问题。
In a project we took over, we added:
在我们接手的一个项目中,我们添加了:
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
return;
}
to the beginning of the constructor of the user controls where this happens to avoid that error.
到用户控件的构造函数的开头,以避免该错误发生。
回答by BernardG
This thread is a little old, but I had a problem I just solved with its help, so I may be able to slightly clarify some points.
这个线程有点旧,但我刚刚在它的帮助下解决了一个问题,所以我可以稍微澄清一些要点。
- Have your solution loaded in Visual Studio as usual.
- Open a 2nd instance of VS, menu debug/attach to process/select devenv. You should see nothing spectacular! In VS 2010, i just get "Disassembly cannot be displayed in run mode."
- Go back to your 1st instance, where your solution is opened. Load or reload the offending XAML file. If you have a problem (I had an exception on a user control, so I could not load that window), the debugger should point the offending code in the 2nd instance. in my case, it was very clear and obvious.
- 像往常一样在 Visual Studio 中加载您的解决方案。
- 打开 VS 的第二个实例,菜单 debug/attach to process/select devenv。你应该看不到什么壮观的东西!在 VS 2010 中,我只是得到“在运行模式下无法显示反汇编”。
- 回到您的第一个实例,您的解决方案在其中打开。加载或重新加载有问题的 XAML 文件。如果您遇到问题(我在用户控件上出现异常,因此无法加载该窗口),调试器应将有问题的代码指向第二个实例。就我而言,这是非常清楚和明显的。
To prevent the offending code from running at design time, I used
为了防止有问题的代码在设计时运行,我使用了
If System.ComponentModel.LicenseUsageMode.Runtime = 1 Then
myObject = New ObjectDefinition
End If
Works perfectly well.
工作得很好。
回答by juFo
In Visual Studio 2015 for WPF:
在 Visual Studio 2015 for WPF 中:
- Hover with your mouse over the "Object reference not set to an instance of an object" in the Design view.
- Wait a (few) second(s) and you will see a popup
- Select "View Exception Details" (you will also see "View Code" and "Delete this element"
- This dialog will show you the exception and the StackTrace
- 将鼠标悬停在“设计”视图中的“未将对象引用设置为对象的实例”上。
- 等待(几)秒,您将看到一个弹出窗口
- 选择“查看异常详细信息”(您还将看到“查看代码”和“删除此元素”
- 此对话框将显示异常和StackTrace
Hope this helps.
希望这可以帮助。
If you do this on the XAML you will just see the exception but not the popup with "View Exception Details", thus you need to do it in the Designer/Design view.
如果您在 XAML 上执行此操作,您将只看到异常而不是带有“查看异常详细信息”的弹出窗口,因此您需要在设计器/设计视图中执行此操作。
回答by astef
I was able to solve the problem after giving a name to an object. It is VS2015, and my markup is different, but it could help somebody too:
在给一个对象命名后,我能够解决这个问题。这是 VS2015,我的标记不同,但它也可以帮助某人:
<ResourceDictionary>
<DataTemplate x:Key="ThisKeySolvesDesignersNullRef"
DataType="local:MyViewModel">
<local:MyControl/>
</DataTemplate>
</ResourceDictionary>
回答by Shahin Dohan
I was having this error today after editing a lot of XAML in my UWP code and I couldn't figure out what was wrong... but after some close inspection, I noticed this mistake I had made:
在我的 UWP 代码中编辑了大量 XAML 后,我今天遇到了这个错误,我无法弄清楚出了什么问题......但是经过一些仔细检查后,我注意到我犯了这个错误:
<Button Click="{Binding MyCommand}" />
I assigned my Command to the Click handler by mistake, and that resulted in a null reference exception... After changing Click to Command, the error went away.
我错误地将我的命令分配给了 Click 处理程序,这导致了一个空引用异常......将 Click 更改为 Command 后,错误消失了。
XAML error reporting needs to be improved!
XAML 错误报告需要改进!


