c# - 如何将模型属性包装在 ViewModel 属性中

标签 c# wpf mvvm prism

我不想将整个 Model 直接暴露给 View,而是希望拥有 ViewModel 属性,这些属性只是每个 Model 的代理 属性。例如;

private Product _product;

public string ProductName
{
     get { return _product.ProductName; }
     set
     {
          SetProperty(ref _product.ProductName, value);
     }
}

但是上面的例子导致了A property, indexer or dynamic member access may not be passed as an out or ref parameter的错误。

我该如何解决这个问题?

附言我的模型不是由 INPC 接口(interface)实现的。它们只是简单的 POCO 类。

最佳答案

您想要的是一个 façade 或 decorator 对象,它将在您的 VM 中充当您的模型,而不是用 ViewModel 属性包装每个模型属性。这使您不仅可以重用您的模型(外观/装饰器),而且还可以将关注点保留在它们所属的位置。您可以像提供的 chipples 一样定义您的属性,但在 setter 中调用 OnPropertyChanged()。包装其他属性时不能使用 SetProperty 方法。

类似的东西:

class Person
{
    public string Name { get; set; }
}

class PersonFacade : BindableBase
{
    Person _person;

    public string Name
    {
        get { return _person.Name; }
        set
        {
            _person.Name = value;
            OnPropertyChanged();
        }
    }
}

class ViewModel : BindableBase
{
    private PersonFacade _person;
    public PersonFacade Person
    {
        get { return _person; }
        set { SetProperty(ref _person, value); }
    }
}

关于c# - 如何将模型属性包装在 ViewModel 属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34676925/

相关文章:

c# - DataTable 在清除和重新填充数据后不更新 DataGrid。 MVVM

使用 IDataErrorInfo 提交 WPF 验证

c# - 如何摆脱 MasterDetailPage 空白空间 Xamarin Forms

c# - 如何以编程方式将单击事件添加到 FrameworkElementFactory

c# - 在 WPF 应用程序中,如何覆盖控制台关闭命令?

c# - 在网格中使用 2 个不同的 ViewModel

javascript - 使用 Aurelia 动态生成 View 中的自定义组件

DataGridTemplateColumn.CellTemplate 中的 wpf 绑定(bind)复选框命令

c# - API 中的访问者模式有什么好处?

c# - 在 ASP.NET C# 中使用未知数量的值查询 SQL 数据库