![](/img/trans.png)
[英]I want to access controls of derive class from base class on onLoad() override in c# (Master page derive from one masterClass)
[英]Derive from base class and override functions
這是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");
}
}
如果是這樣,我應該如何以及在哪里添加此類?
如果沒有,如何覆蓋控件內定義的函數?
這是您可以覆蓋控制方法的方法。 正如您所做的那樣,絕對正確,但是這里有詳細的實現。
這是表格的一部分
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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.