从helper c#中的父调用方法

时间:2013-05-09 13:49:34

标签: c# forms methods callback

我试图从另一个类调用一个方法,但在该方法中,从第一个类调用一个方法......我无法更好地解释,所以这就是我想用代码做的...

MyClass.cs

public static void validarCampos(object sender) {
**some code here**
}

// here, a KeyDown function calls MyHelper.cs=>TextBoxKyeDown method
private void tb_KeyDown(object sender, KeyEventArgs e)
{
    (sender as TextBox).TextBoxKeyDown(e, this);
}

MyHelper.cs

public static void TextBoxKeyDown(this TextBox tb, KeyEventArgs e, Control container)
{
    switch (e.KeyCode)
    {
        case Keys.Enter:
        case Keys.Add:
            tb.ZeroFill(e);
            // I want to call MyClass.cs=>validarCampos(tb);
            // here, before it moves to next TB, because on
            // validarCampos(tb) I can tell if the next TB is
            // enabled or not, if I do not call it HERE
            // when I press ENTER or ADD, it wont move next TB
            // until I press it twice...
            e.SuppressKeyPress = true;
            container.SelectNextControl(tb, true, true, false, true);
            break;
        case Keys.Decimal:
            if ((tb.Tag as string) == "importe")
            {
                e.SuppressKeyPress = true;
                container.SelectNextControl(tb, true, true, false, true);
            }
            break;
        case Keys.Subtract:
            e.SuppressKeyPress = true;
            container.SelectNextControl(tb, false, true, false, true);
            break;
    }
}

真的很抱歉这个解释,如果你需要更多的线索告诉我......我不会粘贴整个validarCampos代码,因为它是~140行...它只是检查TextBoxes的内容并确定哪些是启用的或根据结果​​禁用......

2 个答案:

答案 0 :(得分:3)

这是一个公共静态方法,所以你可以这样称呼它:

MyClass.validarCampos(tb);

答案 1 :(得分:1)

如果帮助方法因上下文而异,请查看Action delagates。您可以将函数作为参数传递给TextBoxKeyDown。我希望该函数看起来像:

void TextBoxKeyDown(this TextBox tb, KeyEventArgs e, Control container, 
                    Action<object> CallBack)
{
   CallBack(tb);
}

可以通过以下方式调用:

(sender as TextBox).TextBoxKeyDown(e, this, validarCampos);