我在Form1上具有此功能,并且我想对Form2Form3等使用相同的功能,而不是在每个表单上重复该功能,有没有办法使所有人都能使用它?我试图制作一个新的Class : Form,然后从表单中调用该函数,但是不起作用...

public void tb_Leave(object sender, EventArgs e)
{
    if ((sender as TextBox).Text.Count() < (sender as TextBox).MaxLength)
        (sender as TextBox).Text = (sender as TextBox).Text.PadLeft((sender as TextBox).MaxLength, '0');
}


更新

感谢您的回答,它们可以正常工作,但是如果我想对X文本框使用相同的方法怎么办? (就像我在使用tb_Leave函数一样)

我的意思是,使用我的旧方法,我只选择X文本框,然后将请假事件发送给我的函数,就像您提到的那样,我需要创建一个方法来在助手类中调用另一个方法...但是我仍然需要创建一个方法在每种形式的内部,打电话给那个班,对吗?虽然,您的答案实际上非常有用,因为我只需要使用我的所有帮助程序类创建一个新的.cs文件:)

更新2
我在迁移此方法时遇到问题

public static void TextBoxKeyDown(this TextBox tb, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Enter:
            case Keys.Add:
                e.SuppressKeyPress = true;
                processTabKey(true);
                break;
            case Keys.Decimal:
                if (tb.Tag == "importe")
                {
                    e.SuppressKeyPress = true;
                    processTabKey(true);
                }
                break;
            case Keys.Subtract:
                e.SuppressKeyPress = true;
                processTabKey(false);
                break;
        }
    }


我当然知道processTabKey();仅适用于活动表单,但是如何使其在de Form类之外起作用?

最佳答案

这是代码的真正简化版本。
要创建在任何地方都可以重用的方法,请创建一个包含简单静态类的新Utility.cs文件。

namespace MyApp.Utilities
{
    public static class MyUtility
    {
        public static void PadForTextBox(TextBox tb)
        {
            if (tb.Text.Length < tb.MaxLength)
                tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
        }
    }
}


现在,您可以从引用了定义类的名称空间的每种形式中调用此方法。

public void tb_Leave(object sender, EventArgs e)
{
    Utility.PadForTextBox(sender as TextBox);
}


获得相同结果的另一种优雅方法是通过TextBox的扩展方法

namespace MyApp.Utilities
{
    public static class TextBoxExtensions
    {
        public static void PadForTextBox(this TextBox tb)
        {
            if (tb.Text.Length < tb.MaxLength)
                tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
        }
    }
}


并用

public void tb_Leave(object sender, EventArgs e)
{
    (sender as TextBox).PadForTextBox();
}


顺便说一句,使用这些方法还可以使您摆脱那种丑陋的演员阵容。

当然,您的tb_Leave方法是一个事件处理程序,应将其链接到文本框。
如果要使应用程序中每个文本框都独立于创建文本框的表单的文本框事件处理程序,则不能依赖WinForm设计器,但需要在Windows的文本框中手动添加事件处理程序。在InitializeComponent调用之后的表单构造函数。总而言之,我更愿意将此任务留给设计人员,并在需要时在上面添加一行。
例如:

InitializeComponent();
// connect the leave event for 3 textboxes to the same static method inside the
// MyUtility static class
textBox1.Leave+=MyUtility.PadEventForTextBox;
textBox2.Leave+=MyUtility.PadEventForTextBox;
textBox3.Leave+=MyUtility.PadEventForTextBox;

.....

public static void PadEventForTextBox(object sender, EventArgs e)
{
    TextBox tb=sender as TextBox;
    if (tb.Text.Length<tb.MaxLength)
        tb.Text=tb.Text.PadLeft(tb.MaxLength, '0');
}

关于c# - 使表格功能可用于所有表格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16213929/

10-11 04:07
查看更多