简体   繁体   English

TextBox的双向绑定

[英]Two way binding for TextBox

This question was asked here for thousands times. 这个问题在这里被问了好几千次。 But really, none of your examples and answers works for me. 但实际上,你的例子和答案都不适合我。 So let me show you my code. 那么让我告诉你我的代码。

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 ignores this binding (nothing changes when I type in textbox, and nothing changes when I change playlist.DriveLetter property. Ofcourse WPF忽略了这个绑定(当我输入文本框时没有任何变化,当我更改playlist.DriveLetter属性时没有任何变化。

Debugger says, that PropertyChanged handler is not null 调试器说,PropertyChanged处理程序不为null

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

So, any ideas what I am doing wrong. 所以,任何想法我做错了什么。 (I do not belive that WPF is wrong)? (我不相信WPF是错的)?

Thanks in advance! 提前致谢!

Change 更改

textBox1.SetBinding(TextBlock.TextProperty, bind); 

to

textBox1.SetBinding(TextBox.TextProperty, bind); 

you don't have to do it this way, even if you want to use your playlist later on. 即使您想稍后使用播放列表,也不必这样做。 Just use a Property in your Window like: 只需在窗口中使用属性,如:

public PlayList PlayList
{
  get;
  private set;
}

and Bind your TextBox like this: 和绑定你的TextBox像这样:

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

you also have to set the DataContext of the Window, I think: 你还必须设置Window的DataContext,我想:

DataContext = this;

or you set the Data Context to your PlayList: 或者将数据上下文设置为PlayList:

DataContext = PlayList;

so the Binding looks like this: 所以Binding看起来像这样:

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

change 更改

 textBox1.SetBinding(TextBlock.TextProperty, bind);

to

 textBox1.SetBinding(TextBox.TextProperty, bind);

You are binding TextBlock's text property rather than TexBox's text property 您绑定TextBlock's文本属性而不是TexBox's text属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM