我在 Visual Studio 2010 和 Blend 4 中的 silverlight 4 Windows Phone 7 项目上使用 MVVM Light 工作得很好一段时间了。 然后突然我开始在 VS 2010 和 Blend 中收到“无法创建“ViewModelLocator”实例”错误。无法弄清楚为什么它现在应该出现。如果某个地方发生了我没有发现的变化,我可以如何追踪任何想法。 我所做的唯一更改(然后放回去)是在用户控件之一的数据上下文表达式前面添加“d:”。我的想法是在设计中进行绑定(bind),但在运行时以延迟的方式进行编程绑定(bind)。
我看到其他人发布了这个问题,但答案提到了 Blend 中的一个错误,该错误显然已得到修复。 VS2010 中也出现这种情况。
App.xaml 看起来像
<Application x:Class="BillSplitter2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:vm="clr-namespace:BillSplitter2.ViewModel"
xmlns:converters="clr-namespace:HardMediumSoft.WP7.Tools.Converters;assembly=HardMediumSoft.WP7.Tools">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/ResourceDictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"/>
<!--Localization String Library-->
<local:LocalizedStrings xmlns:local="clr-namespace:BillSplitter2.Utilities"
x:Key="LocalizedStrings" />
<!--Converters -->
<converters:FloatConverter x:Key="FloatConverter" />
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<converters:StringToBrush x:Key="StringToBrushConverter" />
</ResourceDictionary>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService Launching="Application_Launching"
Closing="Application_Closing"
Activated="Application_Activated"
Deactivated="Application_Deactivated" />
</Application.ApplicationLifetimeObjects>
最佳答案
感谢上面的建议,我开始研究 ViewModel 的构造函数。虽然我没有遇到任何错误,但我确实发现belnd 在事件监听器和处理程序方面存在问题。
我正在使用
if (IsInDesignMode)
{
//populate values here for blend
}
else
{
//runtime initiation
}
填充设计时的一些值。我将通过设置模型中的值的属性来启动它们。这一切都很好,直到我开始根据属性更改添加更复杂的事件处理例程。
为了纠正这个问题并恢复我的“可混合性”,我做了两件事!
- 在 IsDesignMode 部分中设置私有(private)字段而不是属性。这可以避免 PropertyChanged 事件触发。
- 在事件处理程序中添加了 IsInDesignMode 检测,这仍然是一个问题,并跳过任何级联更新。
希望这有帮助!
关于windows-phone-7 - 无法创建 "ViewModelLocator"的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8658967/