因为工作关系,需要做一个新闻列表的控件(Winform),简单的描述为,可以将新闻的标题列举出来,点击新闻标题的时候,可以产生一个事件,把新闻的标题和ID给传递出来。在百度上寻找了很多,发现大家使用开发控件,多是采用了“用户控件”,关于“自定义控件”讲解到的很少,所以我决定自己摸索把类似的一个控件写出来。
首先我们来做一个新闻控件,很简单可以把新闻的标题列出来,点击新闻,可以产生一个点击的事件。
在控件中我们最好可以定义一个NewsEventArgs类,来记录事件的EventArgs
public class NewsEventArg:EventArgs{ public int NewsID = 0; public string NewsTitle = ""; public NewsEventArg(int newsID,string newsTitle){ NewsID = newsID; NewsTitle = newsTitle; } }
然后我们定义一个委托
public delegate void NewsClickEventHandle(object sender,NewsEventArg args);
最后我们来完成,这个控件
public partial class NewsStage : Control { public event NewsClickEventHandle NewsClicked; private Graphics g; public NewsStage() { InitializeComponent(); this.Click += new EventHandler(NewsStage_Click); } //新闻被点击 void NewsStage_Click(object sender, EventArgs e) { if (_NewsID>=0&&_NewsTitle!="") { NewsEventArg myArgs = new NewsEventArg(_NewsID,_NewsTitle); NewsClicked(this, myArgs); } } private int _NewsID = 0; [Description("新闻ID"), Category("Appearance")] public int NewsID { get { return _NewsID; } set { _NewsID = value; this.Invalidate(); } } private string _NewsTitle = ""; [Description("新闻标题"), Category("Appearance")] public string NewsTitle { get { return _NewsTitle; } set { _NewsTitle = value; this.Invalidate(); } } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); g = this.CreateGraphics(); g.DrawString(_NewsTitle, this.Font, new SolidBrush(this.ForeColor), new PointF(0, 0)); } protected void Dispose() { g.Dispose(); } }