0

当我做这样的事情时:

public static void BindData<T>(this System.Windows.Forms.Control.ControlCollection controls, T bind)
    {
        foreach (Control control in controls)
        {
            if (control.GetType() == typeof(System.Windows.Forms.TextBox) || control.GetType().IsSubclassOf(typeof(System.Windows.Forms.TextBox)))
            {
                UtilityBindData(control, bind);
            }
            else
            {
                if (control.Controls.Count == 0)
                {
                    UtilityBindData(control, bind);
                }
                else
                {
                    control.Controls.BindData(bind);
                }
            }
        }
    }

    private static void UtilityBindData<T>(Control control, T bind)
    {
        Type type = control.GetType();

        PropertyInfo propertyInfo = type.GetProperty("BindingProperty");
        if (propertyInfo == null)
            propertyInfo = type.GetProperty("Tag");

// rest of the code....

控件在哪里System.Windows.Forms.Control.ControlCollection,在作为参数传递给这段代码的表单上的控件中有 NumericUpDowns,我在控件集合中找不到它们(controls=myForm.Controls),但是还有其他类型的控件(updownbutton,上下编辑)。问题是我想获得 NumericUpDown 的 Tag 属性,但在使用检查表单控件的递归方法时无法获得它。

4

1 回答 1

1

Tag属性Control类定义。

因此,您根本不需要反思;你可以简单地写

object tag = control.Tag;

您的代码不起作用,因为控件的实际类型(例如NumericUpDown)没有定义单独的Tag属性,GetProperty也没有搜索基类属性。


顺便说一句,在你的第一个if陈述中,你可以简单地写

if (control is TextBox)
于 2010-07-19T13:18:26.253 回答