Retrieve PropertyInfo object using property name

Retrieve PropertyInfo object using property name

Old forum URL: forums.lhotka.net/forums/t/8279.aspx


stuart.bale posted on Sunday, January 03, 2010

This might be simple, but finding an answer has been tricky.

I have a situation where I need to find out if the value of a property has changed, so that I can add it to a list of 'changed properties'.

I've used the FieldManager to check if a field is dirty, using:

this.FieldManager.IsFieldDirty(myPropertyInfo);

However, this method only accepts a PropertyInfo object, and I need to determine if a property has changed from its string name.

Can anyone suggest how I could do this?

Thanks,

Stuart

rxelizondo replied on Sunday, January 03, 2010

I think you are going to need to get a reference to that PropertyInfo one way or another in order to do what you want.

So here is a supper cheese solution:

------------------------------------------

public Csla.Core.IPropertyInfo GetPropInfoByName(string propName)
{
switch (propName)
{
case "prop1":
return prop1Property;

case "prop2":
return prop1Property;

default:
throw new ArgumentException("Prop name not valid");
}
}

------------------------------------------

So now you can do:

this.FieldManager.IsFieldDirty(GetPropInfoByName("ThePropName"));

I didn’t try very hard but I did a quick scan on the CSLA framework and did not find a way to get to the PropertyInfo collection. If there was a way to get to this collection, I guess you could just iterate through such collection searching for a PropertyInfo matching the property name that you are looking for and use that PropertyInfo object to call the FieldManager.IsFieldDirty() method.

I am sure others will be able to come up with a much better solution!

JonnyBee replied on Monday, January 04, 2010

Hi Stuart,

I'd suggest you create intermediate base classes that implements custom funtionality. Look at the MyCsla project on http://cslacontrib.codeplex.com for sample baseclasses.

Then you could add the following method:

    [Browsable(false)]
    public bool IsFieldDirty(string propertyName)
    {
      var propinfo = FieldManager.GetRegisteredProperties().Where(p => p.Name == propertyName).FirstOrDefault();
      // if fieldname does not exist return false (or throw exception).
      if (propinfo == null) return false;

      return FieldManager.IsFieldDirty(propinfo);
    }

stuart.bale replied on Wednesday, January 06, 2010

Awesome Jonny - you're a STAR!

It's the GetRegisteredProperties that i was looking for.

For anyone else referencing this, here is the actual code:

 var propinfo = this.FieldManager.GetRegisteredProperties().Find(p => p.Name == propertyName);

That totally does the trick :-).

Regards,

Stuart

Copyright (c) Marimer LLC