我正在进行一个Windows Phone 8项目,我做了很长时间的WPF和WP7项目中的一些事情,在Windows Phone 8中不起作用。我创建了另一个项目,并复制了这个问题的一个简单版本。我创建了一个新的WP8项目,并执行以下操作:
1)添加一个名为TestVM.cs的新类。
1)添加一个名为TestVM.cs的新类。
class TestVM : DependencyObject
{
public string TestProperty
{
get { return (string)GetValue(TestPropertyProperty); }
set { SetValue(TestPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for TestProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TestPropertyProperty =
DependencyProperty.Register("TestProperty", typeof(string), typeof(TestVM), new PropertyMetadata(string.Empty));
}
2) 修改App.xaml,使<Application.Resources />
看起来像这样:
<!--Application Resources-->
<Application.Resources>
<local:TestVM x:Key="MainVM" />
<local:LocalizedStrings xmlns:local="clr-namespace:VMTest" x:Key="LocalizedStrings"/>
</Application.Resources
3) 将 DataContext="{StaticResource MainVM}"
添加到 MainPage.xaml
。
启动我的应用程序时,我遇到了以下异常:
System.Windows.Markup.XamlParseException: Cannot create instance of type 'VMTest.TestVM' [Line: 11 Position: 29]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at VMTest.App.InitializeComponent()
at VMTest.App..ctor()
有人知道发生了什么事吗?就像我说的,在WP7中,我可以做完全相同的事情,而且它能够正常工作。
TestVM
应该是一个ViewModel
吗?那为什么它是一个DependencyObject
呢? - Federico Berasategui