[英]How to change label color of a usercontrol from another usercontrol ? C# .NET Framework
i have this project with 3 usercontrols and 1 form, the usercontrols appear on the form when a button is pressed.我有这个项目有 3 个用户控件和 1 个表单,按下按钮时用户控件出现在表单上。 Now i need to change a label color on let's say "UserControl3" by clicking a button located in "UserControl1", i tried the following code but it didnt work
现在我需要通过单击位于“UserControl1”中的按钮来更改“UserControl3”上的 label 颜色,我尝试了以下代码但它没有用
var name = new UserControl3();
name.label.ForeColor = Color.Green;
i also tried another way but it threw an exception, image below https://imgur.com/kBHUBoX我也尝试了另一种方法,但它引发了异常,如下图https://imgur.com/kBHUBoX
i then found another way that almost works as intended, by removing and adding the usercontrol.然后我找到了另一种几乎按预期工作的方法,即删除和添加用户控件。 The problem is that then it goes on the main form that is supposed to be empty
问题是然后它继续在应该是空的主窗体上
var name = new UserControl3();
this.Controls.Remove(name);
this.Controls.Add(name);
name.label1.ForeColor = Color.Green;
the code above almost works as i want but i dont think its a good solution and im pretty sure there are other easier ways to make this work... Any kind of help is appreciated.上面的代码几乎可以按我的意愿工作,但我认为这不是一个好的解决方案,而且我很确定还有其他更简单的方法可以使这项工作正常进行……感谢任何形式的帮助。 Thanks
谢谢
You do not have to re-create an instance of usercontrol but use the first instance created and just change the color of the control.您不必重新创建 usercontrol 的实例,而是使用创建的第一个实例并仅更改控件的颜色。
just this code:只是这段代码:
name.label.ForeColor = Color.Green;
Define this code globally全局定义此代码
var name = new UserControl3();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.