如何有共同的子用于特定目的的所有文本框? [英] How to Have Common Sub for a Particular Purpose To All Textboxes?

查看:171
本文介绍了如何有共同的子用于特定目的的所有文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了VS 2010中的C#的WinForms应用程序,我有10个文本框。

I am creating a C# WinForms application in VS 2010. I have 10 TextBoxes.

有关 TextBox1的,我经手的的GotFocus 引发LostFocus ,系统等以下列方式:

For TextBox1, I handled the events for GotFocus, LostFocus, etc. in the following manner:

this.richTextBox1.GotFocus += new System.EventHandler(this.RichTextBox1_GotFocus);
this.richTextBox1.LostFocus += new System.EventHandler(this.RichTextBox1_LostFocus);

private void TextBox1_GotFocus(object sender, System.EventArgs e)
{
    TextBox1.BackColor = Color.White;
}

private void TextBox1_LostFocus(object sender, System.EventArgs e)
{
    TextBox1.BackColor = Color.LightSteelBlue;
}

现在我需要写在同一$ C $下我所有的文本框。它是不是有可能有一个共同的的GotFocus 引发LostFocus 等事件处理程序方法的所有文本框上面做事?

And now I need to write the same code for all of my textboxes. Is it instead possible to have a common GotFocus, LostFocus, etc. event handler method for all textboxes to do the above things?

推荐答案

如果你真的需要这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;
    }
}

这篇关于如何有共同的子用于特定目的的所有文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆