Search code examples
xamarinmvvmdata-bindingmvvmcross

The intended purpose of MvvmCross CreateBindingSet


So I recently came across an interesting scenario from one of my teammates.

They are currently working in a Xamarin project and leveraging MvvmCross. They have decided that they would like to use CreateBindingSet exclusively over bindings directly in xaml.

To me this seems like an anti-pattern for Mvvm. It's tightly coupling the behind code to the view model and it adds extra complexity to a platform that is designed to be bound in xaml.

I'm trying to understand if using this function in behind code is a good idea or not but I can't make heads or tails of it from the documentation.

Can someone tell me what the intended use case is for CreateBindingSet?


Solution

  • In addition to providing text-format binding statement which can be easily included in xml layout files, MvvmCross also provides a C# based syntax to enable bindings to be easily constructed using code.

    This binding syntax is referred to as Fluent bindings.

    For example

    MvvmCross creates the relationship between the View and the ViewModel by the following code:

    var set = this.CreateBindingSet<MyView, MyViewModel>();
    

    Then you can set the data-binding by For and To methods:

    set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName);
    

    With the fluent syntax we can continue to specify the binding type, such as OneWay, and TwoWay, etc, like this:

    set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName).TwoWay();
    

    Fluent binding is especially useful in the iOS and OSX platforms where the Xml layout formats are not easily human-editable(in iOS and MACOS platform there is no such a xml file so we need to set binding in code behind).

    For more details you could check https://www.mvvmcross.com/documentation/fundamentals/data-binding.