Categories
.NET .NET 8 .NET 9 .NET MAUI Android Blazor C# Code Desktop Developer General Hybrid iOS macOS Mobile Toolkit Web What's New Windows Xamarin Xamarin.Forms

Enhance Gesture Binding with the Shared Toolkit

The year 2024 began with an article outlining the improvements in the Shared Toolkit through the optimization of specifying the Binding as a LINQ expression, without requiring an additional getter or setter.

Mainly, the Binding expression is statically typed, providing better control by aiding in identifying errors during compilation. Furthermore, it preserves the default binding behavior of the View, such as the two-way binding in the case of Entry, enabling editing. This behavior can be modified using the BindingMode parameter.

Further, this feature of specifying the binding as LINQ expression has been expanded to encompass Gestures, thereby enhancing code conciseness and ease of maintenance. As is customary, the Gesture methods are also suffixed with v2, such as BindTapGesturev2.

The presented code sample clearly illustrates the significant shift from a block of code to a simple method call.

Before:

new Label()
{
    GestureRecognizers =
    {
        new TapGestureRecognizer().BindCommandv2(static (UserViewModel vm) => vm.NavigateCommand)
    },
}.Center()
 .Bindv2(static (UserViewModel vm) => vm.FullName);

After:

new Label()
    .Center()
    .Bindv2(static (UserViewModel vm) => vm.FullName)
    .BindTapGesturev2(static (UserViewModel vm) => vm.NavigateCommand);

This offers an additional advantage when defined as a Template, with the BindingContext being relative to where it’s used. For such scenarios, the commandSource parameter type is defined as an object which can take any input.

// The template binds to the User model type
// Whereas the Command will be defined in the ViewModel
// So there is a need to relatively reference it
new Label()
    .Center()
    .Bindv2(static (User u) => u.FullName)
    .BindTapGesturev2(static (UserViewModel vm) => vm.NavigateCommand, new RelativeBindingSource(RelativeBindingSourceMode.FindAncestorBindingContext, typeof(UserViewModel)), Binding.SelfPath);

This feature is now part of the v3.3.0 release of the Shared Toolkit in the Stable channel and v4.0.0-preview.2 in the Preview channel. Update now.

If you have any issues or features to suggest, please raise an issue with appropriate details here. Ideas are most welcome.

Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.

By Vijay Anand E G

A software professional with over a decade long industry experience in developing products that spans across desktop, mobile, and web.

One reply on “Enhance Gesture Binding with the Shared Toolkit”

Comments are closed.

Discover more from Developer Thoughts

Subscribe now to keep reading and get access to the full archive.

Continue reading