各种用户控件上的调用方法 [英] Call method on various user controls

查看:21
本文介绍了各种用户控件上的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中创建了许多自定义用户控件.它们是使用 Validates() 方法验证自己的内容的控件.当我单击窗体上的按钮时,我想在具有该方法的任何控件上调用此方法.实现这一目标的最佳方法是什么?

I have created a number of custom user controls in my application. They are controls which validate their own content using a Validates() method. When I click a button on the form, I would like to call this method on any control which has the method. What is the best way to achieve this?

我能够识别控件并检查它们是否具有该方法,但此时不确定如何调用它.(所有控件都以'cc'开头)

I'm able to identify and the controls and check if they have the method, but unsure how to call it at this point. (All the controls begin with 'cc')

        foreach (Control c in this.Controls)
        {
            if (c.Name.Length > 2 && c.Name.Substring(0, 2).Equals("cc"))
            {
                var type = c.GetType();
                if (type.GetMethod("Validates") != null)
                {
                    // Call method here
                }
            }
        }

谁能指出我正确的方向,或者我可以用更好的方法来做到这一点.我希望这些控件将出现在很多表单上,因此我希望从父表单中尽可能轻松地进行分组验证.

Can anyone point me in the right direction, or perhaps a better way I can do this. I expect these controls will be on a lot of forms so i'd like to make a grouped validation as easy as possible from the parent form.

谢谢,

推荐答案

也许尝试使用接口

public interface IValidateMyData
{
    bool Validate();
}

public class ValidationControl : Control, IValidateMyData
{
    // code here
    public bool Validate()
    {
        return true;
    }
}

在您的 Form 中遍历所有控件,但不要检查名称,而是确定控件是否实现了 IValidateMyData 接口:

In your Form iterate over all controls like above but don't check on the name but determine if the control implements the IValidateMyData Interface:

foreach (Control c in this.Controls)
{
    if ( c is IValidateMyData )
    {
        var validationResult = (c as IValidateMyData).Validate();
    }
}

使用此方法,您的控件不必具有特定的名称前缀.

with this method your controls are not bound to have a specific name prefix.

此外,您可以将所有控件上的迭代移动到表单继承的基类中,只需在表单中调用ValidateAllControls()"方法即可.

furthermore you can move the iteration over all controls the validation to a baseclass which your form inherits from and just call the "ValidateAllControls()" Method in your form.

这篇关于各种用户控件上的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆