Skip to main content
 首页 » 编程设计

c#之将文本框数据绑定(bind)到 Form.Text(标题)

2024年02月24日15lyhabc

我正在尝试将 Textbox.Text 绑定(bind)到 Form.Text(它设置表单的标题)。 绑定(bind)本身有效。但是,在我移动整个表单之前,标题不会更新。

如何在不移动表单的情况下更新 Form.Text?我希望在文本框中键入内容时直接更新 Form.Text。

编辑;我在 ToolStripTextbox 触发的 TextChanged 事件中设置了表单的标题:

public partial class ProjectForm : Form 
{ 
   public ProjectForm() 
   { 
       // my code contains all sorts of code here,  
       // but nothing that has something to do with the text. 
   } 
} 
 
private void projectName_TextChanged_1(object sender, EventArgs e) 
{ 
    this.Text = projectName.TextBox.Text; 
} 

和数据绑定(bind)版本:

public partial class ProjectForm : Form 
{ 
   public ProjectForm() 
   { 
       this.projectName.TextBox.DataBindings.Add("Text", this, "Text", true, DataSourceUpdateMode.OnValidation); 
   } 
} 

编辑 2:我发现我忘了说点什么。不知道它是否添加了什么,但我的应用程序是一个 MDI 应用程序。标题变化的部分是:

ApplicationName [THIS CHANGES, BUT ONLY AFTER MOVING/RESIZING] 

请您参考如下方法:

Classic problem, you're not updating the existing form's Text property but a new one that is not visible. Call the Show() method after you change the Text.

Source

您还可以尝试在 TextChanged 事件中使您的表单无效,这样它会强制重新绘制。

编辑 1: 这 StackOverflow question既然你是MDI应用,可能会给你一个答案

编辑 2: 可能是此操作不是线程安全的,因此 UI 线程正在阻塞。因此,您需要调用另一个函数以使其更新。不久前,我在使用 StatusBar 标签时遇到了类似的问题。如果您不知道如何使用委托(delegate),这里有一些示例代码:

public delegate void updateFormTextD(string text); 
 
private void formText(string text) 
{ 
     this.Text = text; 
} 
 
private void updateFormText(string text) 
{ 
     Invoke(new updateFormTextD(formText), text); 
}