Brandon Minnick
Brandon Minnick

Reputation: 15322

Xamarin.Forms: How To Avoid Hard-Coding a String in MVVM Bindings

In Xamarin.Forms, I am creating an MVVM binding for the Button's CommandProperty.

Is there a way to avoid hard-coding the string for the property name?

This way works, but I want to avoid hard-coding a string:

var submitButton = new Button();
submitButton.SetBinding(Button.CommandProperty, "SubmitButtonPressed");

I've found similar answers on StackOverflow that show how to perform type-safety in WinForms, but Xamarin.Forms uses a different binding engine.

Upvotes: 3

Views: 538

Answers (1)

Brandon Minnick
Brandon Minnick

Reputation: 15322

There are two ways that you can use to implement type-safety and avoid hard-coding strings when creating MVVM bindings in Xamarin.Forms

First Way

Reference the View Model and use nameof instead.

var myViewModel = new MyViewModel();
BindingContext = myViewModel;

var submitButton = new Button();
submitButton.SetBinding(Button.CommandProperty, nameof(MyViewModel.SubmitButtonPressed));

Second Way (Deprecated)

Include the View Model as the Type for the SetBinding method and use a Func.

var myViewModel = new MyViewModel();
BindingContext = myViewModel;

var submitButton = new Button();
submitButton.SetBinding<MyViewModel>(Button.CommandProperty, vm => vm.SubmitButtonPressed);

When using this technique, if you refactor the name of the SubmitButtonPressed property in the view model, the new name will percolate up to your view! And you never have to worry about typos again!

Update, 23 Jan 2017

As of Xamarin.Forms v2.3.4, the "Second Way" listed above, setting data bindings using generics, is deprecated. The Xamarin.Forms team explained to me that the generic way was eventually converted to the non-generic way at runtime, and it induced great costs because Expression-parsing is an expensive, CPU-intensive, operation causing performance degradation on mobile devices.

Upvotes: 7

Related Questions