只是为了开始,我对C#和xaml很新.
我已经看过,检查了教程,关于绑定,但是我看到的大部分内容在xaml中创建了一个对象.但是我想在代码中创建对象,然后绑定到它的属性.此外,我将在以后的代码中定义几个对象.一般我想绑定到文本框.
一般来说,我的代码看起来像这样:
MainWindow.xaml.cs
public partial class MainWindow : Window { MyTestObject myTestObject; public MainWindow() { myTestObject= new MyTestObject (); this.DataContext = this; InitializeComponent(); } }
MyTestObject .cs
class MyTestObject : INotifyPropertyChanged { public MyTestObject () { } private string testString = "Test"; public string TestString { get { return testString; } set { if (value == testString) return; testString = value; this.OnPropertyChanged("TestString"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) this.PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } }
最终我会有很多(数值)属性,它将显示在几个文本框中,因为该软件是作为发送测量数据的外部硬件组件的接口.我尝试了几种有约束力的方法,但我还没有成功.我将非常感谢一个例子如何将前面提到的属性绑定到一个TextBox.
解决方法
将Datacontext设置为myTestObject.或者,为myTestObject创建一个公共属性,并将您的Xaml绑定设置为{Binding MyTestObjectPropertyHere.TestString}
例如:
public partial class MainWindow : Window { MyTestObject myTestObject; public MainWindow() { myTestObject = new MyTestObject (); this.DataContext = myTestObject; InitializeComponent(); } }
XAML
<TextBox Text="{Binding Path=TestString}" />
将MainWindow绑定为数据标签的示例:
public partial class MainWindow : Window { MyTestObject myTestObject; public MyTestObject MyTestObjectProperty { get { return myTestObject; } } public MainWindow() { myTestObject = new MyTestObject (); this.DataContext = this; InitializeComponent(); } }
XAML
<TextBox Text="{Binding Path=MyTestObjectProperty.TestString}" />