2010-12-11 64 views
0

我試圖綁定一些文本框來顯示我創建的類的各個字段:你可以使用類對象的數據綁定嗎?

我試過下面的代碼。

MyClass ClassObj = new MyClass(); 
    DataContext = ClassObj; 

    // Create a new binding 
    // Val1 is a variable of type String in MyClass class 
    Binding myNewBindDef = new Binding("Val1"); 

    myNewBindDef.Mode = BindingMode.TwoWay; 
    myNewBindDef.Source = ClassObj; 

    // txtBox1is a TextBlock object that is the binding target object 
    BindingOperations.SetBinding(txtBox1, TextBox.TextProperty, myNewBindDef); 

我添加了一個使用 爲System.Windows.Data和System.ComponentModel,和MyClass的實現INotifyPropertyChanged。但是,當我運行應用程序並更新ClassObj.Val1的值不影響任何內容時,文本框爲空。

我錯過了哪些步驟,還是有更好的方法來做到這一點?

由於

回答

0

啊,事實證明我必須首先讓Val1成爲一個公共變量

1

到INotifyPropertyChanged的另一種方法是,使MyClass的自DependencyObject繼承和創建使用DependencyProperty.Register()函數用於VAL1一個DependencyProperty。 DependencyProperty應該存儲在MyClass的公共級靜態成員中。然後在Val1屬性的getter和setter中使用GetValue()和SetValue()來訪問DependencyProperty。

相關問題