是否可以绑定到Component上的属性

时间:2013-12-13 02:17:25

标签: winforms binding

我有一个定义为:

的组件
public class MyComponent: Component
{
    //constructor, diposal etc omitted for brevity

    public bool MyBool {get; set;}
}

如何绑定MyBool属性?对于实现System.ComponentModel.Component的内容,或者是否必须扩展System.Windows.Forms.Control,这实际上是否可行?

1 个答案:

答案 0 :(得分:0)

我已经设法通过自己的研究找到了答案,我觉得很惊讶,一旦我找到了这个问题就很难找到这个问题的答案:

Component缺少管理绑定所需的属性。要在Visual Studio设计器中创建Component绑定,必须实现IBindableComponent接口。

例如:

public abstract class MyComponent : Component, IBindableComponent
{
    private BindingContext bindingContext;
    private ControlBindingsCollection dataBindings;

    [Category("Data")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public ControlBindingsCollection DataBindings
    {
        get { return dataBindings ?? (dataBindings = new ControlBindingsCollection(this)); }
    }

    [Browsable(false)]
    public BindingContext BindingContext
    {
        get { return bindingContext ?? (bindingContext = new BindingContext()); }
        set { bindingContext = value; }
    }
}

注意:DataBindings属性需要标有[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)],否则设计器中添加的绑定将不会被序列化