C# 将字符串数据绑定到文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10057801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:17:18  来源:igfitidea点击:

Databinding a string to a textbox

c#stringdata-bindingtextbox

提问by Kashif

I'm trying to bind a simple one-line string to a textbox's "text" property but it doesn't seem to be working. What am I doing wrong?

我试图将一个简单的单行字符串绑定到文本框的“文本”属性,但它似乎不起作用。我究竟做错了什么?

string loadedFilename;

textBoxFileName.DataBindings.Add("Current File", loadedFilename, "Text");

I just want to show the user which file they're currently working on using a textbox. I'm using a textbox so that they can copy this string in winforms. (A label won't do that)

我只想使用文本框向用户显示他们当前正在处理的文件。我正在使用文本框,以便他们可以在 winforms 中复制此字符串。(标签不会这样做)

I cannot use an object wrapper because this will cause a cascade of complications down the line in my code. There must be a simple way to do this.

我不能使用对象包装器,因为这会在我的代码中导致一连串的复杂性。必须有一个简单的方法来做到这一点。

采纳答案by Martin

Due to your latest remark about not encapsulating the loadedFilename, I would say: do not use databinding. Instead do it the old fashioned way like

由于您最近关于不封装loadedFilename 的评论,我会说:不要使用数据绑定。而是用老式的方式来做

textBoxFileName.Text = loadedFilename;

Depending on the flow, you can make it an internal propery in the form-code like so

根据流程,您可以像这样在表单代码中将其设为内部属性

internal string Filename {
get { return this.loadedFilename;}
set {
    this.loadedFilename = value;
    textBoxFileName.Text = value;
    }
}

Or set it in the Form_Load event.

或者在 Form_Load 事件中设置它。

Works everytime.

每次都有效。

回答by KRichardson

I would take a look at this other question - Data binding for TextBox

我会看看另一个问题 - TextBox 的数据绑定

Joepro reccomended using INotifyPropertyChanged for your class and then binding the textbox.

Joepro 建议为您的类使用 INotifyPropertyChanged,然后绑定文本框。

回答by Tihomir Tashev

string loadedFilename;

textBoxFileName.DataBindings.Add("Text", loadedFilename, "");

回答by user2432827

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));
   }
 }
}