【发布时间】:2016-06-23 07:11:27
【问题描述】:
我最近刚刚在我的使用 MVVMLight 的 UWP 项目中添加了一个新的 View 和 ViewModel,过去几个小时我一直在试图找出这个和新文件之间的差异,但看不出有什么不同。
这可能是重复的帖子MVVM Light “Type Not Found in cache",但我觉得它从未真正得到回答。
无论如何,我已经在我的 ViewModelLocator 中声明了十几个 ViewModel,它们都按预期工作,除了我的新的,它的定义方式与其他的完全相同:
SimpleIoc.Default.Register<UnlockFeaturesPageViewModel>();
我的 ViewModel 声明如下:
public class UnlockFeaturesPageViewModel : AbstractPageViewModel
{
public UnlockFeaturesPageViewModel(ITelemetryService telemetryService,
IDataService dataservice, CurrentPageEnum currentPage) :
base(telemetryService, dataservice,
CurrentPageEnum.UnlockFeatures)
}
如您所见,它继承自 AbstractPageViewModel 并且该抽象类也非常简单:
public abstract class AbstractPageViewModel : ViewModelBase, IPageViewModel
{
public AbstractPageViewModel(ITelemetryService telemetryService,
IDataService dataservice, CurrentPageEnum currentPage)
{
this._telemetryService = telemetryService;
this._dataService = dataservice;
this._currentPage = currentPage;
}
}
它还包含其他属性,如果需要可以覆盖的方法。 ViewModelBase 是来自 Galasoft.MVVMLight 的类,而 IPageViewModel 是一个基本接口。
InitialComponents(); 时发生错误在 CodeBehind 中被调用并尝试初始化 DataContext,其定义如下:
<Page x:Class="MyApp.Views.UnlockFeaturesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding Source={StaticResource Locator},
Path=UnlockFeaturesViewModel}" >
然后从 ViewModelLocator 调用以下代码,这就是发生错误的地方:
public UnlockFeaturesPageViewModel UnlockFeaturesPageViewModel
{
get
{
return ServiceLocator.Current.
GetInstance<UnlockFeaturesPageViewModel>();
}
}
如果我将鼠标悬停在 上,则会显示以下错误:
'UnlockFeaturesPageViewModel' threw an exception of type
'System.Reflection.TargetInvocationException'
当我执行代码时,它会抛出以下错误:
TargetInvocationException was unhandled by user code
An exception of type 'System.Reflection.TargetInvocationException'
occurred in mscorlib.ni.dll but was not handled in user code.
InnerException 包含以下详细信息:
Message: Type not found in cache: MyApp.Constants.CurrentPageEnum.
Source: GalaSoft.MvvmLight.Extras
StackTrace: at GalaSoft.MvvmLight.Ioc.SimpleIoc.DoGetService(Type
serviceType, String key, Boolean cache) at
GalaSoft.MvvmLight.Ioc.SimpleIoc.MakeInstance[TClass]()
那么为什么我会收到有关在缓存中找不到 MyApp.Constants.CurrentPageEnum 的错误。我已经向我的 CurrentPageEnum 添加了一个新值以匹配新添加的页面,但根据错误,它被缓存在某处并且没有更新。我可能完全错了,但我想不出其他任何东西,因为代码与其他有效的 ViewModel 相同。
它肯定与我的 AbstractPageViewModel 相关,就好像我的 UnlockFeatureViewModel 继承自 ViewModelBase(来自 Galasoft.MVVMLight)一样,它不会引发任何错误。
关于为什么这可能是重复的帖子是因为在另一个类似的帖子中,开发人员提到它根本没有在调试模式下执行以下行,但他没有提到他是如何修复它的。
SimpleIoc.Default.Register<UnlockFeaturesPageViewModel>();
我的问题是它似乎是在调试模式下执行的,因为我正在单步执行它并进入下一行,并且如前所述,该错误仅在尝试将我的页面的 DataContext 设置为该特定时发生查看模型。
奇怪的是Release模式没有出错!
任何想法可能导致此问题以及如何解决此问题?
谢谢。
【问题讨论】:
标签: c# mvvm win-universal-app mvvm-light