我正在尝试将一个简单的单行字符串绑定到文本框的"text"属性,但它似乎不起作用。我做错了什么?
string loadedFilename;
textBoxFileName.DataBindings.Add("Current File", loadedFilename, "Text");
我只想使用文本框向用户显示他们当前正在处理哪个文件。我正在使用一个文本框,以便他们可以在 winforms 中复制此字符串。(标签不会这样做)
我不能使用对象包装器,因为这会导致我的代码中出现一系列复杂情况。必须有一个简单的方法来做到这一点。
由于您最近关于不封装加载文件名的评论,我会说:不要使用数据绑定。而是以老式的方式进行,例如
textBoxFileName.Text = loadedFilename;
根据流程,您可以像这样将其作为表单代码中的内部属性
internal string Filename {
get { return this.loadedFilename;}
set {
this.loadedFilename = value;
textBoxFileName.Text = value;
}
}
或者将其设置为Form_Load事件。
每次都有效。
string loadedFilename;
textBoxFileName.DataBindings.Add("Text", loadedFilename, "");
class Form1:System.Windows.Form, INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
private loadFileName;
public LoadFileName{
get{
return loadFileName;
}
set{
if(this.loadFileName == value ) return;
this.loadFileName = value;
NotifyPropertyChanged("LoadFileName");
}
}
public Form1(){
Initalize();
this.textbox1.DataBindings.Add("Text",this,"LoadFileName");
}
public NotifyPropertyChanged(string propertyName){
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我会看看另一个问题 - 文本框的数据绑定
Joepro建议使用INotifyPropertyChanged为您的类,然后绑定文本框。