【问题标题】:Why am I getting an object reference not set to an instance of an object error? [duplicate]为什么我的对象引用未设置为对象错误的实例? [复制]
【发布时间】:2020-02-25 16:33:29
【问题描述】:

我正在尝试按照示例on this page 将用户控件的数据上下文连接到要提供数据的视图模型。但是,当我这样做时,然后构建项目,我收到“对象引用未设置为对象的实例”错误。我不知道我在这里错过了什么。这是我的用户控件标题中的声明:

<UserControl
    x:Class="PharmacyWarehouse.View.ProgramSelectView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"
    xmlns:convert="clr-namespace:PharmacyWarehouse.View.ValueConverters"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:PharmacyWarehouse.View"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="clr-namespace:PharmacyWarehouse.ViewModel"
    Width="500"
    Height="420"
    Background="Orange"
    mc:Ignorable="d">
    <UserControl.DataContext>
        <vm:ProgramSelectViewModel />
    </UserControl.DataContext>

它在抱怨&lt;vm:ProgramSelectViewModel /&gt;

我不认为这与其他关于 nullreference 的问题和答案重复的原因是因为其他视图和视图模型的编写方式类似并且不会引发 nullreference。

ProgramSelectViewModel 中有超过 500 行,所以我不会在这里复制它。我将提供构造函数:

[PreferredConstructor]
public ProgramSelectViewModel() : this(false) { }

//-----------------------------------------------------------------------------------------
// ProgramSelectViewModel
//-----------------------------------------------------------------------------------------
public ProgramSelectViewModel(bool unit_testing)
{
    Debug.WriteLine($"ProgramSelectViewModel: In constructor; this == {this.ToString()}");
    var connString = MainDataContext.Database.Connection.ConnectionString;
    var userRoles = new DatabaseRolesAndPermissions(connString);
    perms = userRoles.TablePermissions("PW.Program");

    SaveProgramSelectCommand = new RelayCommand(ExecuteSaveProgramSelectCommand, CanSaveProgramSelectCommand);
    CancelProgramSelectCommand = new RelayCommand(ExecuteCancelProgramSelectCommand);

    Messenger.Default.Register<ProceedWithProgramSelectUpdateMessage>(this, UpdateProgramSelect);
    Messenger.Default.Register<OpenProgramSelectMessage>(this, ReadMessageData);
    Messenger.Default.Register<ParentObjectMessage>(this, ReceiveParentObjectMessage);
}

【问题讨论】:

  • 虚拟机长什么样?

标签: wpf data-binding mvvm-light


【解决方案1】:

这个问题很可能是在做你认为它正在做的事情,在 xaml 中实例化一个视图模型(而不是像第二个示例那样隐藏代码)。异常很可能来自 viewmodel 上的某些东西引发了异常。

在调试模式下运行代码并查看断点命中的位置以确定如何解决。

【讨论】:

  • 终于有答案了。与同事交谈(昨天尝试过,但他不在)。他建议我将模态视图的声明移回我已将其移出的资源字典中。 ``` ``` 我将它移到了父 XAML 的资源中,但它在那里不起作用。我想知道为什么将它放在全局资源字典中有效,但在父视图的 XAML 中无效?
  • 创建一个重现问题的任务示例,然后重新提出问题。如果我敢打赌,这可能是与视图模型及其包含的内容有关的问题,而不是它的定义位置
猜你喜欢
  • 1970-01-01
  • 2019-03-20
  • 2023-01-30
  • 1970-01-01
  • 2011-07-09
  • 2012-08-31
  • 2011-11-21
  • 2012-10-01
  • 1970-01-01
相关资源
最近更新 更多