TextBox的双向绑定

msz*_*art 4 c# wpf binding 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

Ofcourse WPF忽略了这个绑定(当我输入文本框时没有任何变化,当我更改playlist.DriveLetter属性时没有任何变化.

调试器说,PropertyChanged处理程序不为null

{Method = {Void OnPropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}}
Run Code Online (Sandbox Code Playgroud)

所以,任何想法我做错了什么.(我不相信WPF是错的)?

提前致谢!

小智 6

更改

textBox1.SetBinding(TextBlock.TextProperty, bind); 
Run Code Online (Sandbox Code Playgroud)

textBox1.SetBinding(TextBox.TextProperty, bind); 
Run Code Online (Sandbox Code Playgroud)