I wrote this post a while back about how to simplify binding properties in Xamarin Forms. Playing around some more with reflection I managed to get rid of the requirement to have a private variable with each property. Instead I create it on the fly which just makes it even easier to create properties now. Let me explain how.
So based on my previous NotifyPropertyChanged.cs class I added a dictionary where I will store all the fields that is created at runtime.
1 |
private Dictionary<string, object> _fields = new Dictionary<string, object>(); |
The Get method will create the property based on the calling methods name the first time it’s called for and after that it will simply return the value:
1 2 3 4 5 6 7 |
protected T Get([CallerMemberName] string propertyName = null) { if (!_fields.ContainsKey(propertyName)) _fields.Add(propertyName, default(T)); return (T)_fields[propertyName]; } |
The Set method will take the referred value and set it to the field with the name of the calling method:
1 2 3 4 5 |
protected void Set(T value, [CallerMemberName] string propertyName = null) { _fields[propertyName] = value; OnPropertyChanged(propertyName); } |
When creating a binding property in a class that inherits from NotifyPropertyChanged we can now simply write like this:
1 2 3 4 5 |
public bool IsBusy { get { return Get(); } set { Set(value); } } |
Now that was a little bit easier than with the previous version of NotifyPropertyChanged now, was’nt it?<
Previous version:
1 2 3 4 5 6 |
private bool _isBusy; public bool IsBusy { get { return _isBusy; } set { SetField(ref _isBusy, value); } } |