Binding RichTextBox.Text to a String

Attempting to bind String to the RichTextBox.Text property so that when the String value changes, this change is reflected in the RichTextBox. So far, I have not been successful.

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

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

Even tried adding rtxt_chatLog.Refresh (); but it does not matter.

Update 1: This also does not work:

 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 misunderstanding data binding?

+6
source share
2 answers

The String class does not implement INotifyPropertyChanged , so there are no events for the binding source to tell RichTextBox that something has changed.

Try updating the class using INotifyPropertyChanged :

 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 the DataBinding does not like the name β€œProperty” for the property name. Try changing it to something other than Property.

 rtxt_chatLog.DataBindings.Add("Text", t, "PropertyText"); 
+4
source

Why not just set the property for the string variable and always process the string through the property? It is easier to do it under the installer: rtxt_chatLog.Text = test;

EDIT: from OP: Well, I want to keep a log of messages in a string in one window (behind the scenes) and then, at user request, pop up another window that will list the contents of the string from the parent form in real time

If you want to list the contents of a string only at the request of the user, you do not need any of this. You just need to process the user request and make rtxt_chatLog.Text = test under this event (possibly some event handler). But if you need your richtextbox to be filled with every new value for your string, you can do something simple:

 public string Test { set { test = value; rtxt_chatLog.Text = test; } get { return test; } } 

The key here is to use only the property through out to set the values ​​of the test variable. For example, in your code do not

 test = "sdf"; 

Do

 test = "sdf"; 

Simple

0
source

Source: https://habr.com/ru/post/906427/


All Articles