Skip to content

Instantly share code, notes, and snippets.

@ionoy
Last active August 29, 2015 14:11
Show Gist options
  • Save ionoy/9356ebb8534a78c1f2b0 to your computer and use it in GitHub Desktop.
Save ionoy/9356ebb8534a78c1f2b0 to your computer and use it in GitHub Desktop.
////////// Usage ///////////
this.BindRadioButtons(v => v.ViewModel.RadioButtonValue,
v => v.RadioButtonA, "A",
v => v.RadioButtonB, "B");
////////// Implementation ///////////
public static IDisposable BindRadioButtons<TSender, TViewModelValue>(this TSender view,
Expression<Func<TSender, TViewModelValue>> viewModelProperty,
Expression<Func<TSender, RadioButton>> button0,
TViewModelValue value0,
Expression<Func<TSender, RadioButton>> button1,
TViewModelValue value1)
{
var d0 = view.BindRadioButton(viewModelProperty, button0, value0);
var d1 = view.BindRadioButton(viewModelProperty, button1, value1);
return new CompositeDisposable(d0, d1);
}
private static IDisposable BindRadioButton<TSender, TViewModelValue>(this TSender view,
Expression<Func<TSender, TViewModelValue>> viewModelProperty,
Expression<Func<TSender, RadioButton>> button,
TViewModelValue value)
{
var isCheckedProperty = typeof(RadioButton).GetProperty("IsChecked", BindingFlags.Instance | BindingFlags.Public);
var isCheckedAccess = Expression.MakeMemberAccess(button.Body, isCheckedProperty);
var isCheckedLambda = Expression.Lambda<Func<TSender, bool?>>(isCheckedAccess, new[] { Expression.Parameter(typeof(TSender), "v") });
var fromViewToViewModel = view.WhenAnyValue(isCheckedLambda)
.Where(check => check.HasValue && check.Value)
.Select(_ => value)
.BindTo(view, viewModelProperty);
var fromViewModelToView = view.WhenAnyValue(viewModelProperty)
.Select(val => val.Equals(value))
.BindTo(view, isCheckedLambda);
return new CompositeDisposable(fromViewModelToView, fromViewToViewModel);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment