【问题标题】:How to determine which property is the default property for databinding?如何确定哪个属性是数据绑定的默认属性?
【发布时间】:2019-11-08 08:33:52
【问题描述】:

给定一个具有多个可绑定属性的 X 类,我如何确定哪个应该是通过反射选择的默认属性?

在 Winforms 设计器中,您可以选择数据绑定。 Visual Studio 如何确定“EditValue”应该是要绑定的默认属性而不是“Text”?

我已经知道如何从对象中获取属性和属性,但是我缺少一些可以告诉我默认使用哪一个的东西。

【问题讨论】:

标签: c# .net winforms reflection windows-forms-designer


【解决方案1】:

你可以依赖类的DefaultBindingProperty 属性。

例如,DateTimePicker[DefaultBindingProperty("Value")] 装饰,而ComboBox[DefaultBindingProperty("Text")] 装饰。

您可以创建如下函数来获取控件的默认绑定属性的名称:

public string GetDefaultBindingPropertyValue(Control c)
{
    var att = c.GetType().GetCustomAttributes(true)
        .OfType<DefaultBindingProperty>().FirstOrDefault();
    return att?.Name;
}

旁注

对于一些复杂的场景,您可能也对这些属性感兴趣:

  • LookupBindingProperties:指定支持基于查找的绑定的属性。 ComboBoxListBox 等列表控件由 [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")] 属性修饰。

  • ComplexBindingProperties:为支持复杂数据绑定的组件指定数据源和数据成员属性。 DataGridView 已被此属性 [ComplexBindingProperties("DataSource", "DataMember")] 修饰。

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2010-12-11
    • 1970-01-01
    相关资源
    最近更新 更多