Mouse On Mars
Mouse On Mars

Reputation: 1132

BindableProperty issue in customized Entry control

I am trying to add a bindable property to an entry in Xamarin.Forms. This should allow me to set/unset the keyboard focus for the Entry by assigning a boolean to the HasFocus property. I am using ReactiveUI as a MVVM framework and the RaiseAndSetIfChanged method raises the INotifyPropertyChanged event implicitly (which works in many other places).

I am not able to hit any breakpoints in my FocusedEntry class and I am not seeing the keyboard coming up. What am I missing?

// XAML
<controls:FocusedEntry Text="My custom Entry"
                       HasFocus="{Binding EntryHasFocus, Mode=TwoWay}"/>

// View Model

private bool _entryHasFocus;
public bool EntryHasFocus
{
    get => _entryHasFocus;
    private set => this.RaiseAndSetIfChanged(ref _entryHasFocus, value);
}

// Custom View
public class FocusedEntry : Entry
{
    public static readonly BindableProperty HasFocusProperty = BindableProperty.Create(
        nameof(HasFocus), typeof(bool), typeof(FocusedEntry), false, BindingMode.TwoWay, propertyChanged: OnHasFocusedChanged);

    public bool HasFocus
    {
        get => (bool)GetValue(HasFocusProperty);
        set => SetValue(HasFocusProperty, value);
    }

    private static void OnHasFocusedChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is FocusedEntry entry)
        {
            bool hasFocus = (bool)newValue;
            bool wasFocused = (bool)oldValue;

            if (hasFocus == wasFocused) return;

            if (hasFocus)
                entry.Focus();
            else
                entry.Unfocus();
        }
    }
}

Upvotes: 0

Views: 118

Answers (1)

Mouse On Mars
Mouse On Mars

Reputation: 1132

The code actually worked all along. For some reason, Visual Studio was not updating the App on my iPad and I was testing with an old version of my app.

Upvotes: 0

Related Questions