2012-08-17 285 views
0

我想通過事件從另一個視圖更新視圖。目前我不知道該怎麼做?從另一個視圖更新視圖

我的案例: 我有一個計算引擎,當我執行計算時,我想告訴用戶有關執行的步驟。所以我打開一個帶有RichTextBox控件的新窗口來顯示所需的信息。當執行新步驟時,我想提出一個事件以便在其他窗口中顯示文本(RichTextBox)。

有沒有可以幫助我做到這一點的例子?

回答

0

基本上,不要直接更改視圖,而是使用模型或「ViewModel」來代替,這是一個好主意。因此,這裏是我的建議:

定義視圖模型進行計算:

public class CalculationViewModel 
{ 
    public event Action ResultChanged; 
    private string _result = string.Empty; 

    public string Result 
    { 
     get { return _result; } 
     set { _result = value; Notify(); } 
    } 

    private void Notify() 
    { 
     if (ResultChanged!= null) 
     { 
      ResultChanged(); 
     } 
    } 
} 

你的看法訂閱了(它顯示的結果你提到的形式)。它將有一個可用於設置模型的屬性。

private CalculationViewModel _model; 
public CalculationViewModel Model 
{ 
    get { return _model; }; 
    set 
    { 
     if (_model != null) _model.ResultChanged -= Refresh; 
     _model = value; 
     _model.ResultChanged += Refresh; 
    }; 
} 

public void Refresh() 
{ 
    // display the result 
} 

你有一段代碼,粘在一起的東西(你可以稱之爲一個控制器,如果你喜歡):

var calculationModel = new CalculationViewModel(); 
var theForm = new MyForm(); // this is the form you mentioned which displays the result. 
theForm.Model = calculationModel; 

var engine = new CalculationEngine(); 

engine.Model = calculationModel; 

此代碼創建的模型,發動機和視圖。該模型被注入到視圖以及引擎中。到那時,視圖訂閱對模型的任何更改。現在,當引擎運行時,它將結果保存到它的模型中。該模型將通知其訂戶。該視圖將接收通知並調用其自己的Refresh()方法來更新文本框。

這是一個簡化的例子。把它作爲一個起點。特別是,WinForms提供了自己的數據綁定機制,您可以利用這種機制,而不是創建一段名爲「Refresh」的代碼,通過使用其DataSource屬性將綁定您的文本框。這要求你也使用WinForm自己的更改通知機制。但是我認爲在繼續讓它在幕後完成之前,你首先需要理解這個概念。

0

剛剛添加它沒有編譯檢查,提防打字錯誤。

public partial class Form1: Form { 
    protected void btnCalculation_Click(object sender, EventArgs e) { 
     var form2 = new Form2(); 
     form2.RegisterEvent(this); 
     form2.Show(); 
     OnCalculationEventArgs("Start"); 
     // calculation step 1... 
     // TODO 
     OnCalculationEventArgs("Step 1 done"); 
     // calculation step 2... 
     // TODO 
     OnCalculationEventArgs("Step 2 done"); 
    } 

    public event EventHandler<CalculationEventArgs> CalculationStep; 
    private void OnCalculationStep(string text) { 
     var calculationStep = CalculationStep; 
     if (calculationStep != null) 
      calculationStep(this, new CalculationEventArgs(text)); 
    } 
} 

public class CalculationEventArgs: EventArgs { 
    public string Text {get; set;} 
    public CalculationEventArgs(string text) { 
     Text = text; 
    } 
} 

public partial class Form2: Form { 
    public void RegisterEvent(Form1 form) { 
     form1.CalculationStep += form1_CalculationStep; 
    } 

    private void form1_CalculationStep(object sender, CalculationEventArgs e) { 
     // Handle event. 
     // Suppose there is a richTextBox1 control; 
     richTextBox1.Text += e.Text; 
    } 
}