将Model绑定到ViewModel的方法

时间:2017-03-22 03:37:16

标签: c# mvvm reactiveui

ReactiveUI中,如果我在ViewModel(INotifyPropertyChanged)后面有一个模型(ReactiveObject),那么最佳做法是什么?我是否在属性的getter和setter中使用该模型:

private Model model;
public string Minky
{
    get { return model.Minky; }
    set 
    { 
      model.Minky = value;
      this.PropertyChanged();
    }
}

或者我应该绑定单个属性:

private string minky;
public string Minky
{
    get { return minky; }
    set { this.RaiseAndSetIfChanged(ref minky, value); }
}

public ViewModel( Model model ) 
{
  if ( model != null ) 
  {
    model.WhenAnyValue( x => x.Minky ).BindTo( this, x => x.Minky );
  }
}

第二个版本似乎是一个好主意(我还可以在没有模型时设置属性)。有什么理由说这是个坏主意吗?

1 个答案:

答案 0 :(得分:2)

在任何MVVM绑定模式中,最佳做法是将“View”绑定到“ViewModel”,此处不使用任何模型。当然,模型然后在数据访问和业务层中用于执行诸如db中的记录或传递给Web服务但不是绑定中的内容。

如果你想使用封装模型出于绑定原因,你应该使用自己的PropertyChanged通知符将模型作为可绑定对象,然后绑定到它们。像这样:

您的ViewModel中有Model

private Model model;
public Model Model
{
    get { return model; }
    set 
    { 
      model = value;
      this.PropertyChanged();
    }
}

然后绑定到属性

this.Bind(ViewModel, x => x.Name, x => x.Model.Minky);

总结:这是一个坏主意。但是如果你想这样做,它会直接绑定到ViewMdel中的模型实例。

相关问题