尝试将字符串绑定(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/