System.Reflection.PropertyInfo.SetValue () يدعو معالج الحدث الافتراضي زر [مغلقة]

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

  •  08-07-2019
  •  | 
  •  

سؤال

لذلك أنا لست متأكدا حقا لماذا يحدث هذا ولكن أنا على التوالي من خلال بعض 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>
هل كانت مفيدة؟

المحلول

وأنا لا يمكن إنتاج هذه مع برنامج قصيرة ولكن كامل بسيط:

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