简体   繁体   English

如何从另一个用户控件更改用户控件的 label 颜色? C# .NET 框架

[英]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.

相关问题 如何在C#中的另一个UserControl中更新UserControl? - How to update UserControl in another UserControl in C#? 如何从另一个UserControl更改一个UserControl并回到第一个(C#)? - How to change a UserControl from another UserControl and get back to the first one ( C# )? 如何从另一个UserControl更改UserControl上的图片框 - How to change picturebox on UserControl from another UserControl C#更改用户控件标签文本和背景色 - C# Change usercontrol labeltext and background color 显示从另一个用户控件 WPF C# 触发的用户控件? - Show Usercontrol triggered from another Usercontrol WPF C#? 从另一个userControl C#访问userControl上的对象 - Accessing an object on userControl from another userControl c# WPF C#如何在另一个UserControl中的一个UserControl中更改按钮的文本? - WPF C# How do i change the Text of a Button that is in a UserControl in another UserControl? 我如何使用C#从另一个用户控件的用户控件调用方法? - How can i call method from usercontrol from another usercontrol using c#? 如何使用 C# 在 Windows Forms 中隐藏另一个用户控件的用户控件 - How can I hide a usercontrol from another usercontrol in Windows Forms using C# C#如何将listview1的项目从usercontrol移动到usercontrol的另一个listview - C# how to move items of listview1 from usercontrol to another listview of usercontrol
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM