System.Reflection.PropertyInfo.SetValue()ボタンのデフォルトイベントハンドラーを呼び出す[終了]

StackOverflow https://stackoverflow.com/questions/309706

  •  08-07-2019
  •  | 
  •  

質問

だから、なぜこれが起こっているのかよくわかりませんが、設定したいコントロール名、プロパティ、値があるDataRowを実行しています。ボタンのTEXTプロパティを設定する場合を除き、すべてが正常に機能します。何らかの理由で、クリックイベントが呼び出されます...

ここに私が持っているコードの一部を示します:

string controlName, value, property;
Control currentControl = null;
System.Reflection.PropertyInfo propertyInfo = null;

// run through all rows in the table and set the property
foreach (DataRow r in languageDataset.Tables[_parentForm.Name].Rows)
{
  controlName = r["ControlName"].ToString().ToUpper();
  value = r["Value"].ToString();
  property = r["Property"].ToString();

  // check all controls on the form
  foreach (Control c in formControls)
  {
    // only change it if its the right control
    if (c.Name.ToUpper() == controlName)
    {
      propertyInfo = c.GetType().GetProperty(property);

      if (propertyInfo != null)
        propertyInfo.SetValue(c, value, null);  ******Calls Event Handler?!?!******
      //

      currentControl = c;
      break;
    }
  }
}

では、なぜ世界で値を設定するときにイベントハンドラーを呼び出すのでしょうか?これが原因で私が設定しているものは次のとおりです:

<SnappletChangePassword>  
  <ControlName>buttonAcceptPassword</ControlName>
  <Property>Text</Property>  
  <Value>Accept</Value>
</SnappletChangePassword>
役に立ちましたか?

解決

単純で短いが完全なプログラムではこれを再現できません:

using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        Button goButton = new Button { 
            Text = "Go!",
            Location = new Point(5, 5)
        };

        Button targetButton = new Button {
            Text = "Target",
            Location = new Point(5, 50)
        };
        goButton.Click += (sender, args) => SetProperty(targetButton, "Text", "Changed");
        targetButton.Click += (sender, args) => MessageBox.Show("Target clicked!");

        Form f = new Form { Width = 200, Height = 120,
                Controls = { goButton, targetButton }
        };
        Application.Run(f);
    }

    private static void SetProperty(object target, string propertyName, object value)
    {
        PropertyInfo property = target.GetType().GetProperty(propertyName);
        property.SetValue(target, value, null);
    }
}

同様に完全なプログラムを思い付くことができますか?

他のヒント

残念ながら、私もそれを再現できませんでした。何が原因かはわかりませんが、修正するために行ったのは、ボタンを削除して元に戻すことだけでした。

それが何であったかはわかりませんが、コードに感謝します。

.Net2.0でそれを書いていませんか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top