Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding RichTextBox.Text to a String

Trying to bind a String to a RichTextBox.Text property so that when the String value changes, that change is reflected in the RichTextBox. So far I'm unsuccessful.

string test = "Test";
rtxt_chatLog.DataBindings.Add("Text",test,null);
test = "a";

This shows "Test" in the rtxt_chatLog, but not the "a".

Even tried adding rtxt_chatLog.Refresh(); but that does not make any difference.

Update 1: This does not work either:

public class Test
{
    public string Property { get; set; }
}

Test t = new Test();
t.Property = "test";
rtxt_chatLog.DataBindings.Add("Text", t, "Property");
t.Property = "a";

Am I not understanding data binding correctly?

like image 966
user983110 Avatar asked Jan 19 '12 19:01

user983110


1 Answers

The String class doesn't implement INotifyPropertyChanged, so there are no events for the binding source to tell the RichTextBox that something changed.

Try updating your class with the INotifyPropertyChanged implemented:

public class Test : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;

  private string _PropertyText = string.Empty;

  public string PropertyText {
    get { return _PropertyText; }
    set {
      _PropertyText = value;
      OnPropertyChanged("PropertyText");
    }
  }

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

}

Also, it looks like DataBinding doesn't like the name "Property" for a property name. Try changing it to something else other than "Property".

rtxt_chatLog.DataBindings.Add("Text", t, "PropertyText");
like image 115
LarsTech Avatar answered Oct 22 '22 16:10

LarsTech