HOW TO:使用程式碼建立繫結
這個範例顯示如何使用程式碼建立和設定 Binding。
範例
FrameworkElement 類別和 FrameworkContentElement 類別都會公開 SetBinding 方法。 如果您要繫結的項目繼承這些類別的任何一個,可以直接呼叫 SetBinding 方法。
下例範例會建立名為 MyData 的類別,其包含名為 MyDataProperty 的屬性。
Public Class MyData
Implements INotifyPropertyChanged
' Events
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
' Methods
Public Sub New()
End Sub
Public Sub New(ByVal dateTime As DateTime)
Me.MyDataProperty = ("Last bound time was " & dateTime.ToLongTimeString)
End Sub
Private Sub OnPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
' Properties
Public Property MyDataProperty As String
Get
Return Me._myDataProperty
End Get
Set(ByVal value As String)
Me._myDataProperty = value
Me.OnPropertyChanged("MyDataProperty")
End Set
End Property
' Fields
Private _myDataProperty As String
End Class
public class MyData : INotifyPropertyChanged
{
private string myDataProperty;
public MyData() { }
public MyData(DateTime dateTime)
{
myDataProperty = "Last bound time was " + dateTime.ToLongTimeString();
}
public String MyDataProperty
{
get { return myDataProperty; }
set
{
myDataProperty = value;
OnPropertyChanged("MyDataProperty");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
}
下列範例顯示如何建立繫結物件來設定繫結的來源。 範例會使用 SetBinding,將 myText (是 TextBlock 控制項) 的 Text 屬性繫結至 MyDataProperty。
Dim data1 As New MyData(DateTime.Now)
Dim binding1 As New Binding("MyDataProperty")
binding1.Source = data1
Me.myText.SetBinding(TextBlock.TextProperty, binding1)
//make a new source
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
如需完整程式碼範例,請參閱Creating a Binding in Code Sample。
您可以使用 BindingOperations 類別的 SetBinding 靜態方法,而不是呼叫 SetBinding。 下列範例會呼叫 BindingOperations.SetBinding 而非 FrameworkElement.SetBinding,將 myText 繫結至 myDataProperty。
Dim myDataObject As New MyData(DateTime.Now)
Dim myBinding As New Binding("MyDataProperty")
myBinding.Source = myDataObject
BindingOperations.SetBinding(myText, TextBlock.TextProperty, myBinding)
//make a new source
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
BindingOperations.SetBinding(myText, TextBlock.TextProperty, myBinding);