2011-12-07 104 views
3

這個問題在這裏被問了幾千次。 但是真的,你的例子和答案都不適合我。 所以讓我告訴你我的代碼。TextBox的雙向綁定

public class PlayList : INotifyPropertyChanged{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void OnPropertyChanged(string name) { 
     var handler = PropertyChanged; 
     if (handler != null) { 
      PropertyChanged(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

    private string _dl; 
    public string DriveLetter { 
     get { return _dl; } 
     set { 
      if (value != _dl) { 
       _dl = value; 
       OnPropertyChanged("DriveLetter"); 
      } 
     } 
    } 
} 

public partial class MainWindow : Window { 
    public PlayList playlist = new PlayList(); 

    private void Window_Loaded(object sender, RoutedEventArgs e) { 
     Binding bind = new Binding("DriveLetter"); 
     bind.Source = this.playlist; 
     bind.Mode = BindingMode.TwoWay; 
     bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
     textBox1.SetBinding(TextBlock.TextProperty, bind); 

     this.playlist.DriveLetter = "A"; 
    } 
} 

Ofcourse WPF忽略,當我在文本框中鍵入此綁定(沒有什麼變化,而當我改變playlist.DriveLetter財產沒有什麼變化。

調試說,那的PropertyChanged處理不爲空

{Method = {Void OnPropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}} 

因此,任何想法我做錯了(我不相信WPF是錯的)?

在此先感謝!

+0

有什麼理由,你爲什麼要構建在代碼而不是XAML的約束力?你有沒有嘗試過使用像[Snoop](http://snoopwpf.codeplex.com/)這樣的工具來調試綁定,或者你是否嘗試在屬性中設置斷點來查看是否有代碼執行? –

+0

是的,有很好的理由。我想稍後在代碼中使用播放列表對象。 – mszubart

+0

我不會說這是這樣做的一個很好的理由。 – snurre

回答

6

變化

textBox1.SetBinding(TextBlock.TextProperty, bind); 

textBox1.SetBinding(TextBox.TextProperty, bind); 
1

變化

textBox1.SetBinding(TextBlock.TextProperty, bind); 

textBox1.SetBinding(TextBox.TextProperty, bind); 

要綁定TextBlock's文本屬性,而不是TexBox's文本屬性

+0

我真的很抱歉。真的很抱歉我的失明(打字速度太快+ InteliSense)。我要去Castorama買一些繩子。浪費了2天。 – mszubart

+1

不要出現這種情況 –

3

即使您想稍後使用您的播放列表,您也不必這樣做。 只需使用一個屬性,你的窗口,如:

public PlayList PlayList 
{ 
    get; 
    private set; 
} 

和綁定你的TextBox這樣的:

<TextBox Text="{Binding Path=PlayList.DriveLetter}"/> 

你還可以設置窗口的DataContext的,我想:

DataContext = this; 

或者您將數據上下文設置爲您的PlayList:

DataContext = PlayList; 

所以綁定看起來像這樣:

<TextBox Text="{Binding Path=DriveLetter}"/> 
+0

+1對於多種方法將代碼示例。 –