2012-10-15 47 views
1

我試圖在XAML我TextBlock的指定數據的變量:OnPropertyChanged和XAML

<TextBlock Name="Test11" Text="{Binding Path=Test}"></TextBlock> 

我使用OnPropertyChanged它:

public partial class MainWindow : Window, INotifyPropertyChanged 

private string _test; 

public event PropertyChangedEventHandler PropertyChanged; 

protected void OnPropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 

public string Test 
     { 
      get 
      { 
       return _test; 
      } 
      set 
      { 
       _test = value; 
       OnPropertyChanged("Test"); 
      } 
     } 

,並試圖在主窗口的構造函數來設置值:

public MainWindow() 
     { 
      InitializeComponent(); 
      Test = "teeest"; 
     } 

但Textblock.Text沒有更新...... 我做錯了什麼?

回答

2

您需要設置datacontext,以便UI知道從何處獲取綁定數據。

public MainWindow() 
{ 
    InitializeComponent(); 
    this.DataContext = this; 
    Test = "teeest"; 
} 
0

在窗口構造後

InitializeComponents()

this.DataContext = this;