In a previous post I described how you can use the ReactiveUI framework to bind properties to both INotifyPropertyChanged and make them Observable to Reactive Extensions (Rx).
The default binding behaviour of the RaiseAndSetIfChanged helper is to assume that a property named “MyProperty” has a backing field called “_MyProperty”. This is not a common convention, and whilst you can explicitly override this behaviour in RaiseAndSetIfChanged, it’s extra work.
Fortunately, the framework offers a way of modifying the default mapping behaviour by binding a different function to RxApp.GetFieldNameForPropertyNameFunc.
Here are a couple of example functions that implement alternative behaviours. The first of which maps to _propertyName and the latter, simply topropertyName.
/// Maps property name MyProperty to field name _myProperty.
Func<string, string> UnderscoreFirstToLowerBehaviour = x =>
{
char[] arr = x.ToCharArray();
arr[0] = char.ToLower(arr[0]);
return '_' + new String(arr);
};
/// Maps property name MyProperty to field name myProperty.
Func<string, string> FirstToLowerBehaviour = x =>
{
char[] arr = x.ToCharArray();
arr[0] = char.ToLower(arr[0]);
return new String(arr);
};
To use one of these behaviours, all you need do is call the following once during app startup:
RxApp.GetFieldNameForPropertyNameFunc = underscoreFirstToLowerBehaviour;
Given this is executed on each notification, I guess the second coding style is more optimal!
p.s. I’m not sure these are the fastest implementations of these conversions, and I’m not going to benchmark, however I did base the code on http://www.dotnetperls.com/uppercase-first-letter who did do some benchmarking on similar code.