派生自基类和覆盖函数

时间:2013-02-26 06:09:53

标签: c# .net winforms

以下是WinForms中标准Label控件的一部分:

public class Label : Control
{
       protected override void OnTextChanged(EventArgs e)
       {
           ...
       }
}

我想覆盖OnTextChanged事件,但我不确定最好的方法。

我应该从Label类派生一个子类,然后覆盖这样的函数吗?

public class Class1 : Label
{
    protected override void OnTextChanged(EventArgs e)
    {
        MessageBox.Show("S");
    }
}

如果是这样,我应该如何以及在哪里添加这个类?

如果没有,我如何覆盖控件内定义的函数?

1 个答案:

答案 0 :(得分:4)

这是您可以覆盖控制方法的方法。正如您所做的那样绝对正确,但详细的实施就在这里。

这是表单部分

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class TestForm : Form
    {
        MyLabel newLable;
        public TestForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            newLable = new MyLabel();
            newLable.Height = 30;
            newLable.Width = 40;
            newLable.Text = "hello";
            this.Controls.Add(newLable);

        }       
    }
}

您也可以使用工具箱中的MyLabel。

MyLabel类是

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

   public class MyLabel:Label
    {

       public MyLabel()
       {

       }
       protected override void OnClick(EventArgs e)
       {
           base.OnClick(e);
           MessageBox.Show("Label Clicked");
       }

    }
}