技术开发 频道

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

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

  场景:1:假设有窗体F,里面有一按钮BtnA,及一Label控件。2:有一类A,里面有一方法Start()。

  要求:点击按钮BtnA后,根据Start()方法里面操作逻辑,将状态显示在Label中。最开始做的时候是实例化类A的时候将整个窗体或者要改变值的控件传入类A中,然后再在类A中操作,可想而知这样是非常不好的。查阅资料后,终于找到了一点解决方法:利用委托或事件,以下是基本代码。

  窗体代码

private void BtnA_Click(object sender, EventArgs e)
   {
   A ms
= new A();
  
//委托方法{实例化类A中定义的委托}
  
//ms.tt= new A.dSetSourceInfo(this.SetInfoOne);
  
//
  
//事件触发{注册类A中定义的事件}
   ms.SetInfo += new EventHandler(ms_SetInfoTwo);
   Thread m
= new Thread(new ThreadStart(ms.Start));
   m.Start();
   }
  
  
  
//委托
  
  
private delegate void mySetInfo(string s);
  
void SetInfoOne(string s)
   {
  
if (this.InvokeRequired)
   {
  
this.Invoke(new mySetInfo(SetInfoOne), s);
  
return;
   }
  
this.Label1.Text = s;
   }
  
  
  
//事件
  
  
void ms_SetInfoTwo(object sender, EventArgs e)
   {
  
if (this.InvokeRequired)
   {
  
this.Invoke(new System.EventHandler(ms_SetInfoTwo), sender);
  
return;
   }
  
this.Label1.Text = (string)sender;
   }

        类A :

public class A
   {
  
//定义事件
   public event EventHandler SetInfo;
  
//类A中执行的事件
   private void SetSourceInfo(object sender, EventArgs e)
   {
  
if (SetInfo!= null) { SetInfo(sender, e); }
   }
  
//
  
//定义委托
   public dSetSourceInfo tt;
  
public delegate void dSetSourceInfo(string str);
  
//类A中执行的方法
   private void SetSourceInfott(string str)
   {
  
if (tt != null) { tt(str); }
   }
  
public A() { }
  
  
/**////
  
/// 开始
  
///
   public void Start()
   {
  
//委托使用
  
//SetSourceInfott("哈哈哈");
  
//Thread.Sleep(1000);
  
//SetSourceInfott("哈哈哈1");
  
//Thread.Sleep(1000);
  
//SetSourceInfott("哈哈哈2");
  
  
//事件使用
   SetSourceInfo("哈哈哈",null);
   Thread.Sleep(
1000);
   SetSourceInfo(
"哈哈哈1",null);
   Thread.Sleep(
1000);
   SetSourceInfo(
"哈哈哈2",null);
   }
   }

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

0
相关文章