从文本框控件继承的组件

问题描述 投票:1回答:1

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

我试图让文本框只能接受数值,如果文本框有超过11个字符,那么它们的字符将以红色显示。

我理解如何从组件类返回一个字符串,但我真的不明白如何将颜色转换为textbox所在的主类的方法。

组件类部分:

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;
        }

    }

add_driver类:

namespace Component
{
    public partial class add_driver : Form
    {
    public add_driver()
    {
        InitializeComponent();
    }

    private void add_driver_Load(object sender, EventArgs e)
    {

    }



    private void phoneNr_textbox_TextChanged(object sender, EventArgs e)
    {

  // IN THIS PART I'M NOT SURE HOW TO CALL METHOD FROM COMPONENT
    }

    private void phoneNr_textbox_KeyPress_1(object sender, KeyPressEventArgs e)
        {
        }
   }
    }
c# visual-studio inheritance methods components
1个回答
0
投票

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

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类中,您将不需要以AddDrivers形式为它们添加事件处理程序。

© www.soinside.com 2019 - 2024. All rights reserved.