Raven Raven - 1 year ago 189
C# Question

How to prevent Xamarin.Forms.Entry Keyboard to be Unfocused when Pressing a Button

I am basically making a chat functionality, and this is how the XAML snippet looks like:

<StackLayout Grid.Row="1" Orientation="Horizontal" HeightRequest="50">
<Entry x:Name="ChatField" Text="{Binding CurrentMessageText}" Placeholder="{Binding MessageTextPlaceHolder}" HorizontalOptions="FillAndExpand"/>
<Button Text="send" BackgroundColor="Transparent" Command="{Binding SendMessageCommand}"/>

I have an Entry control and a button control that is binded to a command that sends the text in the chatfield.

And I would want to mimic the Chat Apps standard wherein pressing the send button does not unfocus or hides the keyboard.

enter image description here

Unfortunately, right now when I press the send button - it automatically unfocus the keyboard from the entry cell.

Initial steps I made to prevent this, is on the ViewModel SendMessageCommand I have:

var chatEntry = CurrentPage.FindByName<Entry>("ChatField");

But this makes a weird behaviour of pushing all the list view up.

enter image description here

Answer Source

Had solved this using a custom renderer on IOS:

    public class ChatEntryViewRenderer : EntryRenderer
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            if (e.PropertyName == VisualElement.IsFocusedProperty.PropertyName)
                if (Control != null)
                    var chatEntryView = this.Element as ChatEntryView;
                    Control.ShouldEndEditing = (UITextField textField) =>
                        return !chatEntryView.KeepOpen; // KeepOpen is a custom property I added and is set on my ViewModel if I want the Entry Keyboard to be kept open then I just set this to true.

            base.OnElementPropertyChanged(sender, e);

What it does is that it basically uses the Control's ShouldEndEditing event that triggers when the EditText loses focus or if its keyboard is about to be unfocused.