Last active
September 16, 2015 23:46
-
-
Save benoitjadinon/8e62dc28d82a20782133 to your computer and use it in GitHub Desktop.
Xamarin.Forms: Chainable and Strongly-Typed SetBinding() Extension
This file contains hidden or 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
| public static class BindableObjectExtensions | |
| { | |
| // chainable, with a string for property | |
| // usage : new Button().WithBinding(Button.CommandProperty, "SomeCommand"), | |
| public static T WithBinding<T>(this T obj, | |
| BindableProperty bindableProperty, | |
| string path, | |
| BindingMode mode = BindingMode.Default, | |
| IValueConverter converter = null, | |
| object converterParameter = null, | |
| string stringFormat = null | |
| ) | |
| where T:BindableObject | |
| { | |
| obj.SetBinding (bindableProperty, new Binding (path, mode, converter, converterParameter, stringFormat)); | |
| return obj; | |
| } | |
| // chainable, with a lambda for property | |
| // usage : new Button().WithBinding(Button.CommandProperty, (MyViewModel vm) => vm.SomeCommand), | |
| public static TOUT WithBinding<TOUT, TVM, TO>(this TOUT obj, | |
| BindableProperty bindableProperty, | |
| Expression<Func<TVM, TO>> sourceProperty, | |
| BindingMode mode = BindingMode.Default, | |
| IValueConverter converter = null, | |
| object converterParameter = null, | |
| string stringFormat = null | |
| ) | |
| where TOUT:BindableObject | |
| where TVM:INotifyPropertyChanged | |
| { | |
| //var name = ((MemberExpression)sourceProperty.Body).Member.Name; | |
| // hack for supporting VMs in VMs | |
| var body = sourceProperty.Body.ToString (); | |
| string name; | |
| if (body.Contains (".")) | |
| name = body.Substring (body.IndexOf (".", StringComparison.Ordinal) + 1); | |
| else | |
| name = body; | |
| obj.SetBinding (bindableProperty, new Binding (name, mode, converter, converterParameter, stringFormat)); | |
| return obj; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment