![](/img/trans.png)
[英]How to append text to the richTextBox from another class in C# Winform?
[英]invoking lable text from another class in c# winform
我目前正在public partial class Form1 : Form
使用此代碼更新public partial class Form1 : Form
this.Invoke((MethodInvoker)delegate
{
Intellisale_Lastprocessed_Item_Label.Text = "example"
}
因為我有大量的UI元素,所以我寧願將所有ui更新代碼放入另一個類中。
因此,我建立了“ UiUpdate”類。
不幸的是,從此類中我收到消息:“表格1不包含Intellisale_Lastprocessed_Item_Label的定義”
可能我忽略了一些確實很簡單的事情,但尚未找到答案。
編輯:
由於這些建議,我將代碼更改為以下內容:
class UiUpdate
{
public void UpdateIntellisale(Form1 form)
{
form.Intellisale_Lastprocessed_Item_Label.text = "example";
}
}
不幸的是,我仍然收到消息,沒有標簽的定義
更新2:
如前所述,標簽在設計師內部定義為私有
您正在static
引用Form1
類 ,而不是對該類的特定實例 。 將所需的實例傳遞給方法:
public void UpdateIntellisale(Form1 form)
{
form.Intellisale_Lastprocessed_Item_Label.Text = "test";
// etc...
}
當您從表單中調用它時,會將其引用傳遞給表單。 如果從表單本身調用,可能是this
。 基本上,您需要您的幫助程序類/方法來知道它使用的是哪種形式。
您需要將Form1
類的對象傳遞給UpdateIntellisale
方法。 喜歡:
class UiUpdate {
public void UpdateIntellisale(Form1 form) {
form.Intellisale_Lastprocessed_Item_Label.text = "test";
}
}
並像這樣調用: UpdateIntellisale(this)
(當然,僅當this
屬於Form1
類時)
存在幾個問題:1.您將標簽視為已定義為Form1的靜態成員。 請改用實例名稱。 例如:
Form1 form = new Form1();
form.Intellisale_Lastprocessed_Item_Label.Text = "example"
// Be aware of an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on." that is throw if you use this code.
請參閱: https : //docs.microsoft.com/zh-cn/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.