c# - 将 RichTextBox.Text 数据绑定(bind)到字符串

标签 c# winforms string data-binding richtextbox

尝试将字符串绑定(bind)到 RichTextBox.Text 属性,以便当字符串值更改时,该更改会反射(reflect)在 RichTextBox 中。到目前为止,我没有成功。

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

这会在 rtxt_chatLog 中显示“Test”,但不会显示“a”。

甚至尝试添加 rtxt_chatLog.Refresh();但这没有任何区别。

更新 1: 这也不起作用:

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";

我是不是没有正确理解数据绑定(bind)?

最佳答案

String 类没有实现 INotifyPropertyChanged,因此绑定(bind)源没有事件来告诉 RichTextBox 发生了一些变化。

尝试使用实现的 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));
  }

此外,DataBinding 似乎不喜欢属性名称的名称“Property”。尝试将其更改为“Property”以外的其他内容。

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

关于c# - 将 RichTextBox.Text 数据绑定(bind)到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931982/

相关文章:

c# - ValidationMessage 和 ValidationMessageFor 之间的区别

c# - 为什么我在附加客户端证书时得到 "Could not create SSL/TLS secure channel"?

c# - 将 Notepad++ REGEX 转换为 .NET C#

c# - 正确显示ToolStripDropDown

Winforms 在单独的线程中执行代码

c++ - 从 C++ 调用 Fortran;返回损坏的字符串

ruby - 什么是 ruby​​ -a 命令行开关?

c# - 从服务器端到 Javascript 的时区不正确

c# - 长时间运行进程的线程选项

swift - 在 Swift 中将字符串转换为 double