2011-12-07 103 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对于多种方法将代码示例。 –