简体   繁体   English

WPF,设计器中的“对象引用未设置为对象的实例”

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

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 .当我尝试为 XAML UserControl重新加载设计器时,出现“未将对象引用设置为对象的实例”错误。 Visual Studio highlights the following line as being the problem: 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}"/>

TemplateDetail is another UserControl . TemplateDetail是另一个UserControl When I view TemplateDetail , its Designer view loads just fine, so I don't think there's a problem there.当我查看TemplateDetail ,它的 Designer 视图加载得很好,所以我认为那里没有问题。 There is a ComboBox in my XAML named cbo_templates that contains instances of my Template class, which has a Data property (hence SelectedItem.Data ).我的 XAML 中有一个名为cbo_templatesComboBox ,它包含我的Template类的实例,它有一个Data属性(因此是SelectedItem.Data )。 However, if I remove .Data from the Path in 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 Path property on null .但是,如果我从上面的 XAML 中的Path中删除.Data ,我仍然会收到“对象引用”错误,所以我认为问题不是我试图访问null上的Path属性。 Here's my ComboBox XAML just in case:这是我的ComboBox XAML 以防万一:

<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 UserControl looks like without running the app.得到这个错误是一个真正的问题,因为设计视图不会加载,所以如果不运行应用程序,我就看不到我的UserControl样子。 Any idea what could be wrong?知道有什么问题吗? It builds fine and I don't see any binding problems in the Build Output.它构建得很好,我在构建输出中没有看到任何绑定问题。

Edit: here is the constructor code for both UserControl s:编辑:这是两个UserControl的构造函数代码:

Constructor of UserControl with "Object reference" error:具有“对象引用”错误的UserControl构造函数:

InitializeComponent();
grd_templateList.DataContext = this; // refers to containing <Grid> in XAML

Constructor of UserControl I'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 DataContext properties, but that didn't help--still getting the "Object reference" error when reloading the Designer.编辑:我尝试在设置它们的DataContext属性之前在构造函数中放置一个if (null != grd_templateList)检查,但这没有帮助 - 重新加载设计器时仍然出现“对象引用”错误。

Edit: the List property that the ComboBox uses is a DependencyProperty .编辑: ComboBox使用的List属性是DependencyProperty I have a default value set in the Register method:我在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 List in the constructor for my UserControl , I still get the error when reloading the Designer.即使我尝试在构造函数中为我的UserControl初始化List ,在重新加载设计器时我仍然会收到错误消息。 I don't think the problem is that List is null or SelectedItem.Data is a bad path.我不认为问题在于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 TemplateData property being bound, apparently.显然,它不喜欢绑定TemplateData属性。

Edit: to add to the mystery, I can view the Design view of my overall/main Window , which includes the UserControl whose Design view gives me the "Object reference" error.编辑:为了增加神秘感,我可以查看我的整体/主Window的设计视图,其中包括UserControl其设计视图给了我“对象引用”错误。 O_o o_o

What Alex says is 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 .假设您在 Visual Studio 中打开了您的项目,打开另一个 Visual Studio 实例并选择Debug->Attach To Process In the dialog which opens select在打开的对话框中选择

  • XDesProc.exe (which is the XAML UI Designer) for VS2012 and newer or XDesProc.exeVS2012 和更新版本的XDesProc.exe (这是 XAML UI 设计器)或
  • devenv.exe for older VS versions. 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 实例中的输出以检查错误究竟是什么。

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 here for detailed information.请参阅此处了解详细信息。

在此处输入图片说明

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.到用户控件的构造函数的开头,以避免该错误发生。

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.为此,请在 Visual Studio 中使用此用户控件打开 Dll 项目。 Select another Visual Studio instance as executable for debugging.选择另一个 Visual Studio 实例作为调试的可执行文件。 Start debugging.开始调试。 In the second (debugged) Visual Studio instance use your user control in the client XAML page.在第二个(调试的)Visual Studio 实例中,在客户端 XAML 页面中使用您的用户控件。 By this way, you can debug user control in design mode.通过这种方式,您可以在设计模式下调试用户控件。

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.这个线程有点旧,但我刚刚在它的帮助下解决了一个问题,所以我可以稍微澄清一些要点。

  1. Have your solution loaded in Visual Studio as usual.像往常一样在 Visual Studio 中加载您的解决方案。
  2. Open a 2nd instance of VS, menu debug/attach to process/select devenv.打开 VS 的第二个实例,菜单 debug/attach to process/select devenv。 You should see nothing spectacular!你应该看不到什么壮观的东西! In VS 2010, i just get "Disassembly cannot be displayed in run mode."在 VS 2010 中,我只是得到“在运行模式下无法显示反汇编”。
  3. Go back to your 1st instance, where your solution is opened.回到您的第一个实例,您的解决方案在其中打开。 Load or reload the offending XAML file.加载或重新加载有问题的 XAML 文件。 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.就我而言,这是非常清楚和明显的。

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.工作得很好。

In Visual Studio 2015 for WPF:在 Visual Studio 2015 for WPF 中:

  1. Hover with your mouse over the "Object reference not set to an instance of an object" in the Design view.将鼠标悬停在“设计”视图中的“未将对象引用设置为对象的实例”上。
  2. Wait a (few) second(s) and you will see a popup等待(几)秒,您将看到一个弹出窗口
  3. Select " View Exception Details " (you will also see "View Code" and "Delete this element"选择“查看异常详细信息”(您还将看到“查看代码”和“删除此元素”
  4. 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 上执行此操作,您将只看到异常而不是带有“查看异常详细信息”的弹出窗口,因此您需要在设计器/设计视图中执行此操作。

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>

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 错误报告需要改进!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM