Search code examples
c#inotifypropertychangedverification

Using TypeDescriptor to check for valid propertyName when using INotifyPropertyChanged


My question is more along the lines of a good practice when using INotifyPropertyChanged.

I've created a base class that implements INotifyPropertyChanged, with the intention that this class will be used in most custom view-model binding circumstance.

Basically I have a DispatchPropertyChange method that takes the name (string) of the property changing. This is pretty straight forward, but strings are obviously error prone.

I would like to verify that the property is valid before dispatching, but I'm not sure if this is a good approach. So far my helper function looks like this.

private void ValidateProperty( string prop )
{
    if( TypeDescriptor.GetProperties(this)[prop] == null )
    {
        //throw error
    }
} 

I'm thinking this strategy could slow things down. Does anyone have another approach, or method of verifying that a property name is valid?


Solution

  • Many implementations (usually slight differences) of dealing with the loosely typed issue of INotifyPropertyChanged.PropertyChanged exist.

    Portion of one example is below; which deals with your null check...

    protected void RaiseChanged<TProperty>(Expression<Func<TProperty>> propertyExpresion)
    {
        var property = propertyExpresion.Body as MemberExpression;
        if (property == null || !(property.Member is PropertyInfo) ||
            !IsPropertyOfThis(property))
        {
            throw new ArgumentException(string.Format(
                CultureInfo.CurrentCulture,
                "Expression must be of the form 'this.PropertyName'. Invalid expression '{0}'.",
                propertyExpresion), "propertyBLOCKED EXPRESSION;
        }
    
        this.OnPropertyChanged(property.Member.Name);
    }