【问题标题】:Windows Phone 8 Viewmodel BindingWindows Phone 8 视图模型绑定
【发布时间】:2013-02-20 03:55:58
【问题描述】:

我正在开发一个 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 中做完全相同的事情,而且它会正常工作。

【问题讨论】:

  • 你能添加整个内部异常吗
  • TestVM 应该是ViewModel 吗?那为什么是DependencyObject?
  • 我强烈推荐使用 MVVM Light,它让这样的事情变得更容易。
  • 奇怪的是,内部没有异常。
  • 尝试公开TestVM

标签: c# xaml mvvm windows-phone-8


【解决方案1】:

您不能在 XAML 中创建未明确标记为公共的对象的实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 2013-12-30
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多