简体   繁体   中英

Databindings for label on a winform usercontrol

I'm creating a usercontrol for a winform app that contains two labels, one as a header and the other one needs to bind to a datasource through Me.usercontrol1.databindings.add() . I'm a novice in usercontrol designing so I searched on internet to find how to make a databindings for my control. I realized that I need to use ControlBindingsCollection but I don't know exactly how.

I found following codes and added to my usercontrol :

Private bindingContext_ As BindingContext
Private dataBindings_ As ControlBindingsCollection
Public Overrides Property BindingContext() As BindingContext
    Get
        If bindingContext_ Is Nothing Then
            bindingContext_ = New BindingContext()
        End If
        Return bindingContext_
    End Get
    Set(ByVal value As BindingContext)
        bindingContext_ = value
    End Set
End Property
<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
Public Overloads ReadOnly Property DataBindings() As ControlBindingsCollection
    Get
        If dataBindings_ Is Nothing Then
            dataBindings_ = New ControlBindingsCollection(Me)
        End If
        Return dataBindings_
    End Get
End Property

Now I can set usercontrol1.databindings parameters but there's obviously something missing because I need to connect a single returning value from this binding to label2.Text in my usercontrol and I don't know how.

Is there anybody to help me solve my problem ?

Thanks in advance.

I don't think you need the code in your question to make this work.

Try making a property that uses that second label in your UserControl:

Property LabelData As String
  Get
    Return Label2.Text
  End Get
  Set(value As String)
    Label2.Text = value
  End Set
End Property

Then your databinding just maps to that property:

myUC.DataBindings.Add("LabelData", testObject, "Text", False, _
                      DataSourceUpdateMode.OnPropertyChanged)

testObject is just a simple class object that has a Text property in this example, which implements the INotifyPropertyChanged interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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