WinFrom通过委托传递事件
今天一个功能需要动态创建pictruebox然后根据时间来倒叙显示,一开始对于这个需求摸不着头脑,后来在公司的大神帮助下实现了,话不多说具体实现上代码了;
1、动态添加控件并倒叙
首先添加一个用户控件里面放pictruebox使其动态创建(用户控件的用法大家自行百度哈)
然后又一个用户控件集合用来排序这个
1 var picture = new CapturePicture() 2 { 3 CreateTime = DateTime.Now 4 }; 5 picture.SetPicture(savePath); 6 picture.Width = pnlCapturePictureList.Width - 24; 7 picture.Margin = new Padding(3); 8 picture.OnPictureClick += Picture_OnPictureClick; 9 pictures.Add(picture); 10 11 DisplayCapturePictures();
这个capturePicture是用户控件,这个OnPictureClick是这个图片的点击事件 这里需要用到委托后面再说如何实现
下面是如何实现倒序的代码
1 private void DisplayCapturePictures() 2 { 3 this.pnlCapturePictureList.Controls.Clear(); 4 var pics = pictures.OrderByDescending(x => x.CreateTime); 5 foreach (var capturePicture in pics) 6 { 7 this.pnlCapturePictureList.Controls.Add(capturePicture); 8 } 9 }
先清除用户控件所有的图片控件
在集合里面的排序好的数据循环添加到用户控件里面就大功告成了。
2,、点击事件的委托
首先定义一个委托,这里这个CapturePictureEventArgs定义字段能实现传参,如果不需要传参可以直接把
CapturePictureEventArgs e 换成 EventArgs e
1 public delegate void CapturePictureClick(object sender, CapturePictureEventArgs e); 2 /// <summary> 3 /// 参数 4 /// </summary> 5 public class CapturePictureEventArgs : EventArgs 6 { 7 public CapturePictureEventArgs(string picturePath) 8 { 9 PicturePath = picturePath; 10 } 11 12 public string PicturePath { get;private set; } 13 }
然后在用户控件里面注册事件
1 //注册事件 2 public event CapturePictureClick OnPictureClick; 3 //picturePath是图片路径是一个参数可以不传 4 private void pictureBox1_Click(object sender, EventArgs e) 5 { 6 if (OnPictureClick != null) 7 { 8 OnPictureClick(this.pictureBox1,new CapturePictureEventArgs(PicturePath)); 9 } 10 }
注册完然后开始调调用
picture.OnPictureClick +=
双击tab键就出来委托事件啦!
1 picture.OnPictureClick += Picture_OnPictureClick;//绑定事件 2 3 private void Picture_OnPictureClick(object sender, CapturePictureEventArgs e) 4 { 5 PictureBox pic = (PictureBox)sender; 6 //释放图片资源 7 img.Dispose(); 8 ImgFrom imgf = new ImgFrom(); 9 imgf.ShowDialog(); 10 int num = 0; 11 string desc = ""; 12 if (imgf.DialogResult == DialogResult.OK) 13 { 14 num = imgf.Num; 15 desc = imgf.Desc; 16 Upload(num, desc, pic); 17 } 18 }
======================================================================最后来个总结吧======================================================================
委托关键字 :delegate
事件关键字:event