2011-08-20 81 views
0

這是我的數據從一個字符串(History.current_commad)到一個文本框(tbCommand)結合:WPF數據綁定不工作

 history = new History(); 

     Binding bind = new Binding("Command"); 

     bind.Source = history; 
     bind.Mode = BindingMode.TwoWay; 
     bind.Path = new PropertyPath("current_command"); 
     bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 

     // myDatetext is a TextBlock object that is the binding target object 
     tbCommand.SetBinding(TextBox.TextProperty, bind); 
     history.current_command = "test"; 

history.current_command正在改變,但文本框沒有被更新。哪裏不對?

感謝

+0

「歷史」課程是什麼樣的? – dlev

+0

public class History {public string current_command; } – Charlie

回答

1

看不到的原因的變化體現在TextBlock是因爲current_command只是一個領域,所以當它被udpated的Binding不知道。

來解決這個問題最簡單的方法是讓你History類實現INotifyPropertyChanged,轉換current_command一個屬性,然後在你的setter方法提高PropertyChanged事件:

public class History : INotifyPropertyChanged 
{ 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propName)); 
     } 
    } 

    private string _current_command; 
    public string current_command 
    { 
     get 
     { 
      return _current_command; 
     } 
     set 
     { 
      if (_current_command == null || !_current_command.Equals(value)) 
      { 
       // Change the value and notify that the property has changed 
       _current_command = value; 
       NotifyPropertyChanged("current_command"); 
      } 
     } 
    } 
} 

現在,當您指定一個值爲current_command,該事件將觸發,並且Binding也將知道更新其目標。

如果你發現自己有很多需要綁定到屬性的類,那麼應該考慮將事件和輔助方法移動到基類中,這樣就不會反覆寫入相同的代碼。

+0

感謝@dlev它很好。我對WPF太天真了。 – Charlie

+0

很高興工作,很高興幫助! – dlev

+0

嗨@dlev,你可以看看這個問題嗎? http://stackoverflow.com/questions/7130143/wpf-xmlns-the-clr-namespace-uri-refers-to-a-namespace-that-is-not-included-in我在做數據綁定的原因代碼是我無法得到正確的xmlns的東西。謝謝 – Charlie