c# - 了解 MVVM : simple non-working code

标签 c# xaml mvvm windows-phone-8

我试图理解这种模式及其背后的所有逻辑。

我认为这并不难,但我仍然在一些简单的任务中失败了。

让我们用我写的一个非工作示例来说明:

模型:

public class Model
{
    public string Name { get; set; }
    public string Description { get; set; }
    public Categories Category { get; set; }
    public Grid PresenterContent { get; set; }
}

View 模型:
public class ViewModel : ViewModelBase
{
    private Model _model;
    public Model Model 
    {
        get
        {
            return _model;
        }
        set
        {
            if (_model != value)
            {
                _model = value;
                RaisePropertyChanged(() => Model);
            }
        }
    }

    public Grid PresenterContent
    {
        get
        {
            return Model.PresenterContent;
        }
        private set { }
    }

    public ViewModel()
    {
        Model = new Model();            
    }
}

看法:
<UserControl.DataContext>
    <Binding Source="ViewModel"/>
</UserControl.DataContext>

<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <ContentPresenter Content="{Binding PresenterContent}"/>        
</Grid>

现在,我希望它在我运行它时能够工作,因为我正在设置 DataContextViewModel其中有一个 PresenterContent属性(property)。

(此属性在 ModelViewModel 中,因为我不知道如何处理 child 的属性,在本例中为 Model.PresenterContent。)

实际发生的是抛出异常:

System.Windows.Data Error: BindingExpression path error: 'PresenterContent' property not found on 'ViewModel' 'System.String' (HashCode=-903444198). BindingExpression: Path='PresenterContent' DataItem='ViewModel' (HashCode=-903444198); target element is 'System.Windows.Controls.ContentPresenter' (Name=''); target property is 'Content' (type 'System.Object')..



这表示没有 PresenterContentViewModel ,这显然是错误的。
如果我尝试绑定(bind)到 Model,异常(exception)情况相同。属性(property)。

我究竟做错了什么?

最佳答案

问题是您将 UserControl.DataContext 绑定(bind)的源设置为字符串 ViewModel 而不是 ViewModel 的实例(这就是为什么您的错误说“在'ViewModel''System.String'上”)

.
为了使其工作,您可以例如使用:

<UserControl.DataContext>
    <vm:ViewModel/>
</UserControl.DataContext>

或者您可以在 App.xaml 或您的 View 资源中定义您的 ViewModel <vm:ViewModel x:Key="myViewModel"/>在你看来使用:
<UserControl.DataContext>
    <Binding Source="{StaticResource myViewModel}"/>
</UserControl.DataContext>

关于c# - 了解 MVVM : simple non-working code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835091/

相关文章:

c# - .NET PictureBox - 如何确保资源已释放

c# - 如何将 xaml 中的值分配给不可绑定(bind)的属性

wpf - 如何使用MVVM Light在wpf 4.0应用程序中实现有/无反馈对话框

c# - 使用 MVVM 范例用 c# 填充组合框

c# - 如何在 Xamarin.Forms 上显示 Word 文件

c# - 继承最派生类型的抽象类

wpf - 在 F# 中访问 XAML (WPF) 元素

c# - 在 XAML 中从 DependecyProperty 绑定(bind)到 DataContext (ViewModel)

c# - 命名管道详细信息

c# - WPF DataGrid 分组与总和和其他字段