3

我有一堂课用来存储我的数据:

class Model
{
   public int Progress{ get; set; }
}

第二类,我可以修改这些数据并通知订阅者有关更改:

class Copy
{
   //...
   public static event EventHandler Changed;
   Model model = new Model();
   ProgressForm progressForm = new ProgressForm();

   public void Start()
   {
      for(int i=0;i<100;i++)
      { 
         model.Progress++;
         if(Changed!=null)
           Changed(this,EventArgs.Empty);
      }
   }

   //...
}

和这样的:

class ProgressForm
{
    Model model;
    public ProgressForm()
    { 
       model = new Model();
       Copy.Changed+=new Changed(ShowProgress);
    }

    void ShowProgress()
    {
       progressBar1.value = model.Progress;
    }
}

如何分别更改每个模型的数据并ProgressForm在运行两个或多个实例时显示此数据Copy

Main()
{
   Copy copy = new Copy();
   copy.Start();
   Copy copy2 = new Copy();
   copy2.Start();
}
4

1 回答 1

1
public class Model
{ 
    public int progress;
    public event EventHandler ProgressChanged;

    public int Progress
    {
        get { return progress; }
        set 
        { 
            progress = value;
            if (ProgressChanged != null)
            {
                ProgressChanged(this, null);
            }
        }
    }
}

public class Copy
{
    public List<Model> models = new List<Model>();
    public event EventHandler CopyProgrss; // FormModel binded to this event. 
    public void AddModel(Model m)
    {
        this.models.Add(m);
        m.ProgressChanged += new EventHandler(m_ProgressChanged);
    }

    void m_ProgressChanged(object sender, EventArgs e)
    {
        Model currentModel = sender as Model;
        int modelProgress = currentModel.Progress;
        if (CopyProgrss != null)
            CopyProgrss(modelProgress,null); // here you can caluclate your over progress. 
    }
}
于 2012-10-28T10:34:05.837 回答