手动触发事件

3

我在表单上有一些控件,我通过设计器为这些控件分配了Leave事件的函数,类似于以下内容:

textBox1.Leave += new System.EventHandler(f1);
textBox2.Leave += new System.EventHandler(f2);
textBox3.Leave += new System.EventHandler(f3);

这些函数对文本框进行一些验证。请注意,并不是所有的文本框都调用相同的委托。

现在我需要做的是,在需要时告诉它们“嘿,触发离开事件”。在我的情况下,我在开始某个地方调用此函数:

private void validateTextBoxes()
{
    foreach (Control c in c.Controls)
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {
            // Fire the tb.Leave event to check values
        }
    }
}

每个文本框都使用自己的代码进行验证。

如果(TB.Leave != null) { TB.Leave(this, new EventArgs()); } - Gavin
如果这是Windows Forms,验证已经完成。 - Nikola Markovinović
Gavin:事件“System.Windows.Forms.Control.Leave”只能出现在+=或-=的左侧。 - Pockets
如果“手动”意味着你自己解雇他们,那你已经做到了。你还要求什么? - Ken Kin
Ken Kin:我在哪里做了那个?VS Designer分配了应该在事件触发时调用的函数,但是除非你编辑(在运行时)一个文本框并离开它,否则事件永远不会被触发。 - Pockets
2个回答

5

我猜想你并不是真的想触发Leave事件,而是想以与Leave事件相同的方式验证文本框,为什么不通过同一个验证方法来运行它们两个呢。

private void ValidateTextBox(TextBox textBox)
{
    //Validate your textbox here..
}

private void TextBox_Leave(object sender,EventArgs e)
{
    var textbox = sender as TextBox;
    if (textbox !=null)
    {
        ValidateTextBox(textbox);
    } 
}

然后连接离开事件。
textBox1.Leave += new System.EventHandler(TextBox_Leave);
textBox2.Leave += new System.EventHandler(TextBox_Leave);
textBox3.Leave += new System.EventHandler(TextBox_Leave);

然后是您的初始验证代码。

private void validateTextBoxes()
{
    foreach (Control c in c.Controls)
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {
            // No need to fire leave event 
            //just call ValidateTextBox with our textbox
            ValidateTextBox(tb);
        }
    }
}

问题在于如何知道哪个验证方法分配给了哪个文本框,因为它们可能不同。 - Pockets

3
作为您当前方法的替代方案,您可能想考虑使用验证事件,这个事件恰好适用于此类情况。
如果您使用验证,那么您可以使用ContainerControl.ValidateChildren()来执行所有子控件的验证逻辑。请注意,Form类实现了ValidateChildren()。
个人认为这就是您应该做的事情。

选择一个验证的位置并不能解决如何调用Leave方法的问题。 - Pockets
这不是一个地方,而是一种方式。你正在重新发明轮子,必然会陷入leave所提供的所有陷阱(无法跳过验证,需要诉诸反射才能调用OnXXXXX事件处理程序),而Windows表单验证已经处理了这些问题。 - Nikola Markovinović

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接