首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作 MVC 模式簡要方法(五):AutoView 實作 IVehicleView、WireUp 連線與 UI 更新邏輯

     編輯:關於C語言

模型實作:ACME2000SportsCar


public class ACME2000SportsCar : Automobile
{
    public ACME2000SportsCar(string name) : base(250, 40, -20, name) {}
    public ACME2000SportsCar(string name, int maxSpeed, int maxTurn, int maxRev) 
        : base(maxSpeed, maxTurn, maxRev, name) {}
}

AutoView 類別:實作 IVehicleView、持有 Control/Model 參考


public class AutoView : UserControl, IVehicleView
{
    private IVehicleControl _control = new AutomobileControl();
    private IVehicleModel _model = new ACME2000SportsCar("Speedy");

    public AutoView()
    {
        InitializeComponent();
        WireUp(_control, _model);
    }

    public void WireUp(IVehicleControl ctrl, IVehicleModel mdl)
    {
        if (_model != null) _model.RemoveObserver(this); // 解除舊觀察
        _model = mdl;
        _control = ctrl;
        _control.SetModel(_model);
        _control.SetView(this);
        _model.AddObserver(this); // 註冊觀察者
    }
}

UI 事件處理:按鈕點擊轉發至控制器


private void btnAccelerate_Click(object s, EventArgs e)
    => _control.RequestAccelerate(int.Parse(txtAmount.Text));

private void btnDecelerate_Click(object s, EventArgs e)
    => _control.RequestDecelerate(int.Parse(txtAmount.Text));

private void btnLeft_Click(object s, EventArgs e)
    => _control.RequestTurn(RelativeDirection.Left);

private void btnRight_Click(object s, EventArgs e)
    => _control.RequestTurn(RelativeDirection.Right);

介面更新邏輯:UpdateInterface


public void UpdateInterface(IVehicleModel auto)
{
    lblStatus.Text = $"{auto.Name} heading {auto.Direction} at speed: {auto.Speed}";
    pBar.Value = auto.Speed > 0 
        ? auto.Speed * 100 / auto.MaxSpeed 
        : auto.Speed * 100 / auto.MaxReverseSpeed;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved