2012-08-17 224 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; 
    } 
}