【问题标题】:Could not create an instance of ViewModelLocator whenever an instance of a model in a different assembly is initialized每当初始化不同程序集中的模型实例时,都无法创建 ViewModelLocator 实例
【发布时间】:2013-03-18 17:05:07
【问题描述】:

这是我第一次在 StackOverflow 上发帖(虽然它在过去帮了我很多)而且通常我什至不必发帖,因为我假设的问题已经回答了。但是这个我真的找不到合适的解释。

所以我在修改 C#、Entity Framework 4、WPF 和 MVVM Light。我已经制作了一个程序集,用作各种模型、视图和视图模型的库,用于特定目的。

现在我正在制作另一个用于不同目的的组件。但是,在第一个程序集中已经提供了一些必需的方法和视图。所以我想我要将第一个程序集的引用添加到第二个程序集,然后从第一个程序集创建模型的实例到第二个程序集的模型或 ViewModel。

一切都没有错误地构建。但是当我检查第二个程序集中的视图的设计视图时,这部分有锯齿状的下划线:

<UserControl.Resources>
    <vm:ViewModelLocator x:Key="Locator" />
</UserControl.Resources>

当您查看设计视图时,顶部栏上会出现一个错误,其中包含以下文字:

Object reference not set to an instance of an object.
   at Powell.Materials.Common.ViewModel.MaterialsViewViewModel.SetupLists() in E:\Projects\Software\Powell Marketing\Powell\Powell\Materials\Powell.Materials.Common\ViewModel\MaterialsViewViewModel.cs:line 514
   at Powell.Materials.Common.ViewModel.MaterialsViewViewModel..ctor() in E:\Projects\Software\Powell Marketing\Powell\Powell\Materials\Powell.Materials.Common\ViewModel\MaterialsViewViewModel.cs:line 601

有人遇到过这种类型的错误吗?或者有没有合适的方法来做这种事情?

【问题讨论】:

  • 你能发帖MaterialsViewViewModel.SetupLists()吗?我很确定,在那里可以找到错误。
  • private void SetupLists() { Retrieve retrieve = new Retrieve(secretKey, IDUser, connectionName); unitListProperty = retrieve.RetrieveUnits(); matlTypeProperty = retrieve.RetrieveMaterialTypes(); supplierListProperty = retrieve.RetrieveSuppliers(); } 它在自己的模型中调用一个方法,该方法与来自引用程序集的模型进行通信。

标签: c# wpf mvvm entity-framework-4 mvvm-light


【解决方案1】:

在代码中,我看到了 NullReferenceException 的 4 个可能来源。

  • secretKey
  • IDUser
  • connectionName
  • retrieve(尽管这可能被正确实例化)

我不知道前三个来自哪里。所以检查它们的值。我很确定其中之一是null。如果所有三个都正确实例化,请检查最后一个。

【讨论】:

  • 只要程序运行,它们就会立即实例化。但是既然您已经提到它,我想我应该为每个声明一个默认值。非常感谢:D
猜你喜欢
  • 2012-01-29
  • 2012-05-27
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多