如何在ViewModel属性中包装Model属性

Ste*_*ung 2 c# wpf prism mvvm

我没有直接将整个Model暴露给View,而是希望拥有ViewModel属性,它们只是每个Model属性的代理.例如;

private Product _product;

public string ProductName
{
     get { return _product.ProductName; }
     set
     {
          SetProperty(ref _product.ProductName, value);
     }
}
Run Code Online (Sandbox Code Playgroud)

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

我该如何解决这个问题?

PS我的模型不是由INPC接口实现的.它们只是简单的POCO类.

Bri*_*nas 7

你想要的是一个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); }
    }
}
Run Code Online (Sandbox Code Playgroud)