Created
October 21, 2015 07:32
-
-
Save buehler/b420231f68b20085d2b2 to your computer and use it in GitHub Desktop.
Base view model for Xamarin bindings. Contains helper methods for setting a field and notify the binding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Foundation; | |
using System.Runtime.CompilerServices; | |
using System; | |
namespace ViewModels | |
{ | |
public class BaseViewModel : NSObject | |
{ | |
public event EventHandler PropertyChanged = delegate{}; | |
protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) | |
{ | |
WillChangeValue(propertyName); | |
field = value; | |
DidChangeValue(propertyName); | |
PropertyChanged(this, null); | |
} | |
protected void SetField<T>(ref T field, T value, string propertyName, params string[] additionalProperties) | |
{ | |
foreach (var prop in additionalProperties) | |
{ | |
WillChangeValue(prop); | |
} | |
WillChangeValue(propertyName); | |
field = value; | |
DidChangeValue(propertyName); | |
foreach (var prop in additionalProperties) | |
{ | |
DidChangeValue(prop); | |
} | |
PropertyChanged(this, null); | |
} | |
} | |
public class DemoViewModel : BaseViewModel | |
{ | |
private string _str; | |
[Export("Str")] | |
public string Str | |
{ | |
get { return _str; } | |
set { SetField(ref _str, value); } | |
} | |
private string _strWithOtherBindings; | |
[Export("StrWithOtherBindings")] | |
public string StrWithOtherBindings | |
{ | |
get { return _strWithOtherBindings; } | |
set { SetField(ref _strWithOtherBindings, value, "StrWithOtherBindings", "OtherBinding"); } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment