Windows Phone 8 Viewmodel绑定

Mat*_*edy 3 c# xaml mvvm windows-phone-8

我正在开发一个Windows Phone 8项目,我正在做一些我在WPF和WP7中做了很多年的事情,它似乎在Windows Phone 8中不起作用.我创建了另一个项目,并重现了一个更简单的问题形式.我创建了一个新的WP8项目,并执行以下操作:

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));
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

任何人都知道发生了什么事吗?正如我所说,我可以在WP7中做同样的事情,它会正常工作.

Mat*_*edy 7

您无法在XAML中创建未标记为显式公共的对象实例.