从另一个视图更新视图

时间:2012-08-17 09:02:09

标签: c# .net .net-4.0 richtextbox

我想通过事件从另一个视图更新视图。目前我不知道该怎么做?。

我的案例: 我有一个计算引擎,当我执行计算时,我想告知用户所执行的步骤。因此,我打开一个带有RichTextBox控件的新窗口,以显示所需的信息。执行新步骤时,我想引发一个事件,以便在另一个窗口中显示文本(RichTextBox)。

有没有一个例子可以帮助我做到这一点?

2 个答案:

答案 0 :(得分:0)

基本上,最好不要直接更改视图,而是操作模型或“ViewModel”。所以这就是我的建议:

定义用于计算的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提供了自己的数据绑定机制,您可以利用它,而不是创建一段名为“刷新”的代码,您可以使用其DataSource属性将文本框绑定到模型中。这要求您也使用WinForm自己的更改通知机制。但我认为你需要首先理解这个概念,然后才能在幕后完成。

答案 1 :(得分: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;
    }
}