C#类中操作UI层控件状态

作者:互联网   出处:控件中国网   2014-11-05 19:19:18   阅读:2

一直以来都是接触B/S开发,很少做C/S开发,线程就用得更少了,最近做一些工作中用到的小软件终于用上了线程,记录一些心得.

  场景:

  1:假设有窗体F,里面有一按钮BtnA,及一Label控件.

  2:有一类A,里面有一方法Start().

  要求:

  点击按钮BtnA后,根据Start()方法里面操作逻辑,将状态显示在Label中.

  最开始做的时候是实例化类A的时候将整个窗体或者要改变值的控件传入类A中,然后再在类A中操作,可想而知这样是非常不好的.

  查阅资料后,终于找到了一点解决方法:利用委托或事件,以下是基本代码.

  窗体代码

1 private void BtnA_Click(object sender, EventArgs e)
  2 {
  3 A ms = new A();
  4 //委托方法{实例化类A中定义的委托}
  5 //ms.tt= new A.dSetSourceInfo(this.SetInfoOne);
  6 //或
  7 //事件触发{注册类A中定义的事件}
  8 ms.SetInfo += new EventHandler(ms_SetInfoTwo);
  9 Thread m = new Thread(new ThreadStart(ms.Start));
  10 m.Start();
  11 }
  12
  13
  14//委托
  15
  16 private delegate void mySetInfo(string s);
  17 void SetInfoOne(string s)
  18 {
  19 if (this.InvokeRequired)
  20 {
  21 this.Invoke(new mySetInfo(SetInfoOne), s);
  22 return;
  23 }
  24 this.Label1.Text = s;
  25 }
  26
  27
  28//事件
  29
  30 void ms_SetInfoTwo(object sender, EventArgs e)
  31 {
  32 if (this.InvokeRequired)
  33 {
  34 this.Invoke(new System.EventHandler(ms_SetInfoTwo), sender);
  35 return;
  36 }
  37 this.Label1.Text = (string)sender;
  38 }

  类A

1 public class A
  2 {
  3 //定义事件
  4 public event EventHandler SetInfo;
  5 //类A中执行的事件
  6 private void SetSourceInfo(object sender, EventArgs e)
  7 {
  8 if (SetInfo!= null) { SetInfo(sender, e); }
  9 }
  10 //或
  11 //定义委托
  12 public dSetSourceInfo tt;
  13 public delegate void dSetSourceInfo(string str);
  14 //类A中执行的方法
  15 private void SetSourceInfott(string str)
  16 {
  17 if (tt != null) { tt(str); }
  18 }
  19 public A() { }
  20
  21 /**////
  22 /// 开始
  23 ///
  24 public void Start()
  25 {
  26 //委托使用
  27 //SetSourceInfott("哈哈哈");
  28 //Thread.Sleep(1000);
  29 //SetSourceInfott("哈哈哈1");
  30 //Thread.Sleep(1000);
  31 //SetSourceInfott("哈哈哈2");
  32
  33 //事件使用
  34 SetSourceInfo("哈哈哈",null);
  35 Thread.Sleep(1000);
  36 SetSourceInfo("哈哈哈1",null);
  37 Thread.Sleep(1000);
  38 SetSourceInfo("哈哈哈2",null);
  39 }
  40 }

  以上为一些简单的应用,其它复杂的基本上都可以按照这一招来做.

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat