samedi 20 août 2022

Setting Event handler in properties of object using reflection

In a C# / WPF App, I have an abstract UI that allows to display and modify the content of objects given.

Change in the objects are detected by the "PropertyChanged" event (PRISM) and the callback needs to be set.

The objects are derived from a base class and contains properties, some of these properties can be also editable objects and contains enumerable, each items of those needs to be set the PropertyChanged action.

Whilst this can be easily done from the child class which has the knowledge of the content of the object, I would like to keep that code on the base class, which doesn't necessarily knows the content of the derived object.

The goal is to loop through the object events and check whether the "PropertyChanged" exists in which case we assign it.

This is as far as I've gotten, but does not work

    void SetModifiedCallback(object src)
    {
        PropertyInfo[] properties = src.GetType().GetProperties();
        
        foreach (PropertyInfo property in properties)
        {
            var value = property.GetValue(src);
            
            if ((property.GetType() != typeof(string)) && 
                (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)))
            {
                var col = (IEnumerable)value;
                
                if (col != null)
                {
                    foreach (var item in col)
                    {
                        if (item.GetType().IsSubclassOf(typeof(BindableBase)))
                        {
                            (item as BindableBase).PropertyChanged += Recipe_PropertyChanged;
                        }
                    }
                }
            }
        }
    }




Aucun commentaire:

Enregistrer un commentaire