1 | initial version |
A custom Entry can be bound in Xamarin Forms by following these steps:
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.