【问题标题】:System.Reflection.PropertyInfo.SetValue() calling default event handler of button [closed]System.Reflection.PropertyInfo.SetValue() 调用按钮的默认事件处理程序[关闭]
【发布时间】:2008-11-21 18:31:58
【问题描述】:

所以我不太确定为什么会发生这种情况,但我正在运行一些 DataRows,其中有我想要设置的控件名称、属性和值。一切正常,除非我设置按钮的 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>

【问题讨论】:

  • 您确定它调用的是 Click 处理程序而不是 TextChanged 处理程序吗?现在尝试重现 - 有趣的一个......

标签: winforms reflection c#-2.0


【解决方案1】:

我无法用一个简单的短而完整的程序来重现这一点:

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);
    }
}

你能想出一个类似完整的程序来演示它吗?

【讨论】:

    【解决方案2】:

    很遗憾,我也无法复制它。我不确定是什么原因造成的,但我所做的只是删除按钮并将其放回原处。

    不确定它是什么,但感谢您的代码。

    你不是用 .Net2.0 写的吧?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多