Skip to content

Instantly share code, notes, and snippets.

@brendanmckenzie
Last active July 11, 2016 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendanmckenzie/7de67a8315628c336b107032dc25b2cd to your computer and use it in GitHub Desktop.
Save brendanmckenzie/7de67a8315628c336b107032dc25b2cd to your computer and use it in GitHub Desktop.
class MvvmModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
internal bool _ignoreUpdate = false;
protected void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
static class Mvvm
{
public static void Bind<TViewModel, TResult>(TViewModel viewModel, Expression<Func<TViewModel, TResult>> expression, UITextField textField)
where TViewModel : MvvmModel
{
var propertyName = (expression.Body as MemberExpression).Member.Name;
var viewModelType = typeof(TViewModel);
var viewModelProperty = viewModelType.GetProperty(propertyName);
viewModel.PropertyChanged += (sender, e) =>
{
if (viewModel._ignoreUpdate) { return; }
if (e.PropertyName == propertyName)
{
textField.Text = viewModelProperty.GetValue(sender, null) as string;
}
};
textField.AddTarget((sender, e) =>
{
viewModel._ignoreUpdate = true;
viewModelProperty.SetValue(viewModel, textField.Text, null);
}, UIControlEvent.EditingChanged);
}
}
class VenueDetailViewModel : MvvmModel
{
string _proprietor;
public string Proprietor { get { return _proprietor; } set { _proprietor = value; OnPropertyChanged(nameof(Proprietor)); } }
public string BusinessName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment