MVVM-Light:在ViewModel中包装模型属性的最佳实践,其中不能使用Set <t>

时间:2015-05-26 15:40:02

标签: c# mvvm mvvm-light

在MVVM-Light中,ViewModelBase类有一个Set方法:

protected bool Set<T>(ref T field, T newValue = default(T), bool broadcast = false, [CallerMemberName] string propertyName = null);

该方法的目标是封装您可能希望在设置属性(属性更改通知,消息传递等)时发生的各种副作用。

我希望通过委托给Model的getter / setter,通过ViewModel中的属性公开我的Model的属性。例如,对于学生(模型),我目前正在ViewModel中实现Student.Name包装器,如下所示:

public class ViewModelBaseWrapped<T> : ViewModelBase where T: DomainObject {
    public ViewModelBaseWrapped(T wrapped) {
        m_wrappedDomainObject = wrapped;
    }

    private T m_wrappedDomainObject;
    protected T Wrapped { get { return m_wrappedDomainObject; } }
}

public class StudentViewModel : ViewModelBaseWrapped<Student> {
    public StudentViewModel(Student wrapped) : base(wrapped) { }
    public string FirstName {
        get { return Wrapped.FirstName; }
        set { Wrapped.FirstName = value;  }
    }
}

但是,我更喜欢使用ViewModelBase的Set函数,以便访问其他封装功能:

public class StudentViewModel : ViewModelBaseWrapped<Student> {
    public StudentViewModel(Student wrapped) : base(wrapped) { }
    public string FirstName {
        get { return Wrapped.FirstName; }
        set { Set(ref Wrapped.FirstName, value);  }
    }
}

然而,这是非法的,因为你不能通过ref传递对象的属性。任何人都可以想到一种方法来使用Set架构,同时仍然能够推迟使用Model作为后备存储吗?

0 个答案:

没有答案