2013-05-28 37 views
1

我試圖做一個簡單的綁定,但我遇到了一些問題。我有一個文本塊和一個按鈕。文本塊綁定到一個名爲「word」的屬性。當你按下按鈕時,單詞的數值發生變化,我想自動更新文本塊。這是一個典型的例子,請給我解釋一下我做錯了什麼:超級簡單綁定示例

namespace WpfApplication5 
{ 
    public partial class MainWindow : Window, INotifyPropertyChanged 
    { 

     private string _word; 

     public string word 
     { 
      get { return _word; } 
      set 
      { 
       _word= value; 
       RaisePropertyChanged(word); 
      } 
     } 

     private void change_Click(object sender, RoutedEventArgs e) 
     { 
      word= "I've changed!"; 
     } 


     #region INotifyPropertyChanged Members 

     public event PropertyChangedEventHandler PropertyChanged; 

     private void RaisePropertyChanged(string propertyName) 
     { 
      if (this.PropertyChanged != null) 
       this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 

     #endregion 


    } 
} 

我與綁定XAML:

<Window x:Class="WpfApplication5.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TextBlock HorizontalAlignment="Left" Margin="210,152,0,0" TextWrapping="Wrap" Text="{Binding word}" VerticalAlignment="Top"/> 
     <Button x:Name="change" Content="Change" HorizontalAlignment="Left" Margin="189,235,0,0" VerticalAlignment="Top" Width="75" Click="change_Click"/> 
    </Grid> 
</Window> 

回答

2

你提出一個PropertyChanged事件名爲I've changed!屬性,因爲你通過的屬性wordRaisePropertyChanged。你需要通過名稱的屬性,而不是

RaisePropertyChanged("word"); 

這個回答假設的數據上下文設置正確。如果沒有,你需要修復:

DataContext = this; 
+0

謝謝,我沒有注意到「」之前。我如何設置DataContext?我試圖「this.DataContext;」在InitializeComponent()之前;但它不會讓我這樣做。 – Sturm

+0

@Sturm:請參閱更新。 –

+0

我真的很感謝你的幫助,工作!我現在準備好進一步學習一些真正的約束力。順便說一句,你如何綁定這樣的財產,但在其他類? (不是代碼隱藏的MainWindow)。例如,如果我有Data.cs類與該詞屬性分隔? – Sturm