Windows Phone 8视图模型绑定

3
我正在进行一个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));
}

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中,我可以做完全相同的事情,而且它能够正常工作。


你能添加整个内部异常吗? - Zaki
那个 TestVM 应该是一个 ViewModel 吗?那为什么它是一个 DependencyObject 呢? - Federico Berasategui
1
我强烈推荐使用MVVM Light,它可以让这样的事情变得更加容易。 - robertk
奇怪的是,没有内部异常。 - Matthew Kennedy
3
尝试将TestVM设为公共的。 - Denis
  1. 转换到MVVM Light是正确的计划。还有许多其他好处。
  2. @Denis:就是这样。TestVM不是公共的。
- Matthew Kennedy
1个回答

7
在XAML中,如果对象没有明确标记为public,则无法创建该对象的实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接