用可视控件包装模型

本文关键字:模型 包装 控件 可视 | 更新日期: 2023-09-27 18:06:06

如果您有一个简单的数据模型实例。

class AppleModel
{
   int PipCount = 3;
   Boolean isFresh = true;
}

你想对这个做一个视觉控制:

class AppleView : PictureBox
{
    private AppleModel _model; 
    public AppleView( AppleModel model )
    {
         this._model = model;
         .........
    }
}

是否有一种机制允许AppleView访问AppleData的属性?

例如:

AppleModel Model = new AppleModel();
AppleView View = new AppleView(Model);
View.PipCount = 99;
//not View.Model.PipCount = 99;
Console.WriteLine(Model.PipCount.ToString()); //99

用可视控件包装模型

是否有一种机制允许AppleView访问属性

是的,它们被称为属性在c#中,对象可以通过重新声明属性来轻松地将属性转发给它的一个成员:

class AppleModel
{
   int PipCount { get; set; }    // Auto Property
   Boolean isFresh {get ; set; } // Auto Property
}
class AppleView : PictureBox
{
  private AppleModel _model; 
  public AppleView( AppleModel model )
  {
         this._model = model;
     .........
  }
  int PipCount 
  { 
   get { return this._model.PipCount; } 
   set { this._model.PipCount = value; }
  }
  int isFresh 
  { 
   get { return this._model.PipCount; } 
   set { this._model.PipCount = value; }
  }
}