0

我有各种在我的表单上动态创建的文本框,当它们被创建时,添加了数据绑定,将文本框绑定到我的类中的一个属性。

我需要能够获得对文本框的引用,但是我只知道文本框绑定到的属性。那么是否有可能获得对文本框的引用,只知道它绑定到的属性的名称。

我希望我已经正确解释了这一点!

4

1 回答 1

4

如果我理解正确,您可以在Form类中尝试此方法:

public Control GetControlByDataBinding(string key)
{
    foreach (Control control in Controls)
    {
        foreach (Binding binding in control.DataBindings)
        {
            if (binding.PropertyName == key) return control;
        }
    }

    return null;
}

或者使用Linq甚至更好:

public Control GetControlByDataBinding(string key)
{
    return 
        Controls
        .Cast<Control>()
        .FirstOrDefault(control => 
            control.DataBindings
            .Cast<Binding>()
            .Any(binding => binding.PropertyName == key));
}
于 2012-11-04T23:04:32.377 回答