c# - 将 Model 绑定(bind)到 ViewModel 的方法

标签 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();
    }
}

或者我应该绑定(bind)单个属性:
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 );
  }
}

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

最佳答案

在任何 MVVM 绑定(bind)模式中,最佳实践是将“ View ”绑定(bind)到“ View 模型”,此处不使用模型。当然,模型随后用于数据访问和业务层,以执行诸如在数据库中记录或传递给 Web 服务但不在绑定(bind)中的操作。

如果您出于绑定(bind)的原因想要使用封装的模型,您应该将模型设置为可绑定(bind)的对象,并拥有自己的PropertyChanged。通知器,然后绑定(bind)到它们。像这样:

您有一个 Model在您的 View 模型中

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

然后绑定(bind)到属性
this.Bind(ViewModel, x => x.Name, x => x.Model.Minky);

所以总结 : 这是个坏主意。但如果你想直接绑定(bind)到 ViewMdel 中的模型实例。

关于c# - 将 Model 绑定(bind)到 ViewModel 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42942294/

相关文章:

c# - 在 c# .net 中关闭另一个应用程序

wpf - 依赖注入(inject) : Assigning User Controls to Specific Grid Cells

wpf - wpf usercontrol-MVVM模式-如何确定加载时间

c# - Xamarin ReactiveUI - 您在应用程序错误中引用了 ReactiveUI 的可移植版本

c# - 准时制。序列化为 json 的最佳方式

c# - 使用 Agility Pack 用另一个节点包围现有节点

.net - WPF MVVM 取消窗口关闭

c# - 处理没有 View 的 ViewModel 中的异常(在 ReactiveUI 中)

c# - Splat.Locator 一个 ViewModel 的多个 View

c# - 如何在另一个 session 中更新具有惰性属性的对象(代理对象)?