2013-11-14 104 views
11

剛開始,我對C#和xaml很陌生。wpf 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)); 
    } 
} 

最終我將有相當多的(數值)屬性,它們將顯示在幾個文本框中,因爲s oftware旨在作爲發送測量數據的外部硬件組件的接口。我嘗試了幾種綁定方式,但我還沒有成功。我將非常感謝如何將前面提到的屬性綁定到TextBox的示例。

回答

16

將Datacontext設置爲myTestObject。或者,使公共財產的myTestObject和設置您的XAML綁定到{結合MyTestObjectPropertyHere.TestString}

例如:

public partial class MainWindow : Window 
{ 
    MyTestObject myTestObject; 

    public MainWindow() 
    { 
     myTestObject = new MyTestObject(); 

     this.DataContext = myTestObject; 

     InitializeComponent(); 

    } 
} 

的XAML

<TextBox Text="{Binding Path=TestString}" /> 

實例與綁定到主窗口作爲datacontext:

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}" /> 
+1

如果我最終將有幾個對象,那麼我相信我無法設置的DataContext到myTestObject,因爲後來我將不能夠他們的休息綁定?在這種情況下,猜測公共財產會是一種方式嗎? – xnonamex

+1

xnonamex:是的,如果您要綁定到MainWindow中的多個不同對象,則爲公共屬性。我會用一個例子來更新。 –