2010-12-11 49 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。

相关问题