且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何有共同的子用于特定目的的所有文本框?

更新时间:2023-12-06 16:32:34

如果你真的需要这10个不同的文本框,在***的(和大多数面向对象的)做是创建件事自己的自定义文本框控件,继承自 System.Windows.Forms.TextBox

If you really need this for 10 different textboxes, the best (and most object-oriented) thing to do would be to create your own custom textbox control that inherits from System.Windows.Forms.TextBox.

既然你从基文本框类继承,你得到它的所有功能是免费的,你也可以实现你想要的自定义行为。然后,只需使用该自定义控件作为简易替换为任何你想要与你的窗体上的这种行为控制的标准文本框控件。这样,您就不必附上任何事件处理程序了!该行为被内置到您的控制,下面的封装和鸵鸟政策重复自己动手的指导方针。

Since you're inheriting from the base TextBox class, you get all of its functionality for free, and you can also implement the custom behavior that you want. Then just use this custom control as a drop-in replacement for the standard textbox control wherever you want controls with this behavior on your form. This way, you don't have to attach any event handlers at all! The behavior is built right into your control, following the guidelines of encapsulation and don't-repeat-yourself.

Sample类:

public class FocusChangeTextBox : TextBox
{
    public FocusChangeTextBox()
    {
    }

    protected override void OnGotFocus(EventArgs e)
    {
        // Call the base class implementation
        base.OnGotFocus();

        // Implement your own custom behavior
        this.BackColor = SystemColors.Window;
    }

    protected override void OnLostFocus(EventArgs e)
    {
        // Call the base class implementation
        base.OnLostFocus();

        // Implement your own custom behavior
        this.BackColor = Color.LightSteelBlue;
    }
}