从文本框控件继承的组件

时间:2019-02-06 14:10:09

标签: c# visual-studio inheritance methods components

我正在尝试创建一个从文本框控件继承控件的组件(Visual Studio 2017,使用C#的Web窗体应用程序)。

我正在尝试使文本框只能接受数字值,并且如果文本框包含11个以上的字符,则N个字符将以红色显示。

我了解如何从组件类中返回字符串,但我并没有真正了解如何将将颜色更改为文本框所在的主类的方法。

组件类部分:

BodyPublishers.ofInputStream

add_driver类:

public partial class textbox : Component
   {
       public textbox()
       {
           InitializeComponent();
    }

    public textbox(IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

//METHOD TO BE USED IN add_drivers
    public void textBox1_TextChanged(object sender, EventHandler e)
    {
        if (textBox1.MaxLength > 11)
        {
            textBox1.ForeColor = Color.Red;
        }

    }

1 个答案:

答案 0 :(得分:0)

您需要在KeyPress类中处理textbox事件,该事件应继承自现有TextBox类-否则,您将需要重新创建所有现有的{{1 }}!另外,请注意,C#中类和方法名称的标准大小写为CamelCase,而不是snake_case或pascalCase。

TextBox

您可能需要处理一些其他的极端情况,或者可能希望添加一些生物舒适感以简化新组件的使用(例如,添加一个属性以直接获取数字值,而不是使用每次public partial class MyTextBox : TextBox { public MyTextBox() { InitializeComponent(); } protected override void OnTextChanged(object sender, EventArgs e) { if (this.Text.Length > 11) { this.ForeColor = Color.Red; } } protected override void OnKeyPressed(object sender, KeyPressedEventArgs e) { // check for a number, set e.Handled to true if it's not a number // may need to handle copy-paste and other similar actions } } 属性)。

鉴于您已将这些方法添加到Text类中,因此您将不需要MyTextBox形式的事件处理程序。