-1

インターフェイスとデリゲートを介して別のスレッドからラベルを更新しようとしています。デバッグ モードでは、ラベル プロパティがメッセージに設定されていると表示されます。しかし、フォーム自体には何も見えません。

.NET 4.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クラスがインターフェイスを処理する方法が問題の原因であると思われます。しかし、私はその理由や正確な理由を理解できません。

4

1 に答える 1

1

Textプロパティは、新しいとして初期化されているため、コードを呼び出すときに以前に読み込まれColoLblた では変更されません。作成された新しいインスタンスでのみ変更される場合がありますForm1iMessageListener.SetMessage("Show my message");iMessageListener Form1();

IMessageListener iMessageListener = new Form1();

ColoLbl以前に初期化された の値を変更しようとしている場合はForm1、 の新しいインスタンスを初期化しないでくださいForm1。代わりに、以前に作成IMessageListenerした にリンクする を初期化します。Form1

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

 

//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");

ありがとう、
これがお役に立てば幸いです:)

于 2012-12-17T10:31:30.877 に答える