views:

39

answers:

2

Here is the problem:

I have a property of a certain object. This property is of Type t. I need to find out, if a string value can be attached to this property.

For example: I have an instance of a Windows.Controls.Button. I need a mechanism, that will return true for property Button.Background, but false for Button.Template.

Can anybody help? Thanks a lot

A: 
public static bool PropertyCheck(this object o, string propertyName)
{
    if (string.IsNullOrEmpty(propertyName))
        return false;
    Type type = (o is Type) ? o as Type : o.GetType();

    PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);

    if (pi != null && pi.PropertyType == typeof(string))
        return true;

    return false;
}

and then Invoke it like this:

object someobj = new Object();
if (someobj.PropertyCheck("someproperty"))
     // do stuff

or you could do it like this:

Type type = typeof(someobject);
if (type.PropertyCheck("someproperty"))

this has some limitations as you then cannot check the Type type itself for properties, but you can always make another version of that if it is needed.

I think this is what you wanted, hope it helps

Richard J. Ross III
This example returns true for all properties, whose types are string. That is not exactly what I need. I need to find out all the properties, whose value can be set in XAML by a string. See an example I gave in a previous post with the Background and Template. Thanks for reaction anyway
Gal
+1  A: 

I think you take the problem in the wrong direction :

The property does not accepts directly String: actually the property is converted to the good type if a converter exists.

You then may look if a converter exist using this code :

public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString)
{
   // Checks to see if the value passed is valid.
   return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))
            .IsValid(aString);
}

These pages may interest you too :

  1. http://msdn.microsoft.com/en-us/library/aa970913.aspx
  2. http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
Jmix90
Thanks a lot - this pointed me a good direction, although the exact code I needed is this:return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty)).CanConvertFrom(typeof(String));
Gal
Nice ! Have a lot of fun with it :-)
Jmix90