Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A custom Entry can be bound in Xamarin Forms by following these steps:

  1. Create a custom Entry class by inheriting from the Entry class in Xamarin.Forms namespace.
  2. Add a BindableProperty to the custom Entry class to enable data binding for it.
  3. Implement the OnBindingContextChanged method in the custom Entry class to set the value of the BindableProperty based on the binding context.
  4. Use the custom Entry in a XAML file and bind it to a property in the view model.

Here is an example implementation of a custom Entry with data binding:

CustomEntry.cs:

using Xamarin.Forms;

public class CustomEntry : Entry
{
    public static readonly BindableProperty TextProperty = BindableProperty.Create(
        nameof(Text),
        typeof(string),
        typeof(CustomEntry),
        null,
        propertyChanged: OnTextPropertyChanged);

    public string Text
    {
        get => (string)GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }

    private static void OnTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var customEntry = (CustomEntry)bindable;
        customEntry.Text = (string)newValue;
    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        if (BindingContext != null)
        {
            SetBinding(TextProperty, new Binding(nameof(Text), BindingMode.TwoWay));
        }
    }
}

In the OnBindingContextChanged method, we check if the binding context is not null and then create a binding for the Text property with a two-way binding mode.

CustomEntryPage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CustomEntryPage"
             xmlns:local="clr-namespace:MyApp.CustomControls">

    <StackLayout>
        <local:CustomEntry Text="{Binding UserName}" />
    </StackLayout>

</ContentPage>

In the XAML file, we use the custom entry and bind its Text property to a property named UserName in the view model.

With this implementation, any changes made to the custom entry's Text property will automatically update the bound property in the view model, and any changes made to the bound property will be reflected in the custom entry's Text property.