Reflection, drive me crazy!

Zipping my code to the maximum has made me take the hard to understand but powerful way of .NET Reflection.

This crazy ViewModel plays with DataWrappers (a concept from the Cinch Framework by Sacha Barber). I modified the framework to add a feature that makes it even better in a reflection-wise approach.

Take a look at this method of the ViewModel:

private void DataWrapperOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
            var dataWrapper = (DataWrapperBase) sender;

            if (!dataWrapper.IsValid)

            var dataValue = dataWrapper.GetPropertyValue("DataValue");
            var dataWrapperName = dataWrapper.ParentPropertyChangeArgs.PropertyName;

            var targetPropertyName = GetTargetPropertyName(dataWrapperName);

                TargetItems.SetPropertyToAll(targetPropertyName, dataValue);
            catch (TargetException ex)

It takes the DataWrapper, its current DataValue and its name. Then, translates (optionally) the name of the property (the equivalent property in the actual object of the model) and applies the value to the analogous property of each target item (TargetItems is an IEnumerable).

It can be improved even more (applying value conversion because sometimes the target and source properties may not be of the same type, for example), but it works pretty good. And the best of this is that I saved A LOT of boring cloned lines.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s