C# 标签未通过接口更新

C# 标签未通过接口更新,c#,winforms,multithreading,interface,C#,Winforms,Multithreading,Interface,试图通过接口和委托从另一个线程更新我的标签。在调试模式下,它表示标签属性已设置为消息。但我看不到形式本身 在.NET4.0中工作 我正在使用的内容的一个小图示: 我的界面: public interface IMessageListener { void SetMessage(string message); } 我实施它的形式: public partial class Form1 : Form, IMessageListener { ... public void SetM

试图通过接口和委托从另一个线程更新我的标签。在调试模式下,它表示标签属性已设置为消息。但我看不到形式本身

在.NET4.0中工作

我正在使用的内容的一个小图示:

我的界面:

public interface IMessageListener
{
    void SetMessage(string message);
}
我实施它的形式:

public partial class Form1 : Form, IMessageListener
{
...
    public void SetMessage(string message)
    {
        SetControlPropertyValue(ColoLbl, "Text", message);
    }

    delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
    private void SetControlPropertyValue(Control oControl, string propName, object propValue)
    {
        if (oControl.InvokeRequired)
        {
            SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
            oControl.Invoke(d, new object[] { oControl, propName, propValue });
        }
        else
        {
            Type t = oControl.GetType();
            PropertyInfo[] props = t.GetProperties();
            foreach (PropertyInfo p in props.Where(p => p.Name.ToUpper() == propName.ToUpper()))
            {
                p.SetValue(oControl, propValue, null);
            }
        }
    }
 }
我试图通过接口设置消息的类。该类正在从另一个线程运行:

public class Controller
{
    IMessageListener iMessageListener = new Form1();
    ...
    public void doWork()
    {
        iMessageListener.SetMessage("Show my message");
    }
 }
代码编译得很好,当逐步调试标签的属性时,由于某种原因,它不会显示在表单本身上


我怀疑可能是我在某个地方漏掉了一行,或者是
Controller
类处理接口的方式导致了问题。但是我不知道确切的原因或原因。

ColoLbl
Text
属性在调用
iMessageListener.SetMessage(“显示我的消息”)之前加载的
Form1
中不会更改iMessageListener
被初始化为新的
Form1(),所以在代码中使用code>它只能在创建的新实例中更改

IMessageListener iMessageListener = new Form1();
如果您试图更改以前初始化的
Form1
中的
ColoLbl
值,请不要初始化
Form1
的新实例。相反,初始化一个链接到先前创建的
Form1
IMessageListener

示例

//myFormSettings.cs
class myFormSettings
{
    public static Form1 myForm1; //We will use this to save the Form we want to apply changes to
}

谢谢,

我希望这对您有所帮助:)

尝试刷新表单!将
IMessageListener
参数添加到
controller
构造函数中,并使
IMessageListener listener=this在表格1中。这解决了问题。谢谢你的帮助。@FlorisPrijt我很高兴你的问题得到了解决。祝你今天愉快:)
//Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
    myFormSettings.myForm1 = this; //Set myForm1(the form we will control later) to this
    Form2 X = new Form2(); //Initialize a new instance of Form2 as X which we will use to control this form from
    X.Show(); //Show X
}
//Form2.cs
IMessageListener iMessageListener = myFormSettings.myForm1;
iMessageListener.SetMessage("Show my message");