C# 自定义控件

因为工作关系,需要做一个新闻列表的控件(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(); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值