简体   繁体   English

如何确定哪个属性是数据绑定的默认属性?

[英]How to determine which property is the default property for databinding?

Given a Class of X that has multiple properties that are bindable, how do I determine which one should be the default property to select via reflection?给定 X 的 Class 具有多个可绑定的属性,我如何通过反射确定哪个应该是 select 的默认属性?

In the Winforms designer you can select Databinding.在 Winforms 设计器中,您可以 select 数据绑定。 How does Visual Studio determine that "EditValue" should be the default property to bind to rather than say "Text"? Visual Studio 如何确定“EditValue”应该是要绑定的默认属性而不是“Text”?

在此处输入图像描述

I already know how to get properties and attributes from the object, but I'm missing something that would tell me which one to use as default.我已经知道如何从 object 获取属性和属性,但是我缺少一些可以告诉我默认使用哪一个的东西。

You can rely on DefaultBindingProperty attribute of the class.您可以依赖 class 的DefaultBindingProperty属性。

For example a DateTimePicker is decorated with [DefaultBindingProperty("Value")] but a ComboBox is decorated with [DefaultBindingProperty("Text")] .例如, DateTimePicker[DefaultBindingProperty("Value")]装饰,但ComboBox[DefaultBindingProperty("Text")]装饰。

You can create a function like following, to get name of the default binding property of a control:您可以创建一个 function 如下所示,以获取控件的默认绑定属性的名称:

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

Side Note边注

You may be interested to these attributes as well for some complex scenarios:对于一些复杂的场景,您可能也对这些属性感兴趣:

  • LookupBindingProperties : Specifies the properties that support lookup-based binding. LookupBindingProperties :指定支持基于查找的绑定的属性。 List controls like ComboBox and ListBox are decorated by this attribute, [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")] .ComboBoxListBox这样的列表控件由这个属性修饰, [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")]

  • ComplexBindingProperties : Specifies the data source and data member properties for a component that supports complex data binding. ComplexBindingProperties :指定支持复杂数据绑定的组件的数据源和数据成员属性。 DataGridView has been decorated by this attribute, [ComplexBindingProperties("DataSource", "DataMember")] . DataGridView已被此属性修饰, [ComplexBindingProperties("DataSource", "DataMember")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM