Setting the Focus to an Entry in Xamarin.Forms

后端 未结 6 875
天命终不由人
天命终不由人 2020-12-20 13:58

This is just a simplified example, but I\'m trying to set this up so that when I open up this page in my Application, the first thing that happens is the keyboard pops up re

6条回答
  •  半阙折子戏
    2020-12-20 14:20

    In one of my projects I did something like this. Please try the following example:

    public class EntryFocusBehavior : Behavior
    {
        public string NextFocusElementName { get; set; }
    
        protected override void OnAttachedTo(Entry bindable)
        {
            base.OnAttachedTo(bindable);
            bindable.Completed += Bindable_Completed;
        }
    
        protected override void OnDetachingFrom(Entry bindable)
        {
            bindable.Completed -= Bindable_Completed;
            base.OnDetachingFrom(bindable);
        }
    
        private void Bindable_Completed(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(NextFocusElementName))
                return;
    
            var parent = ((Entry)sender).Parent;
            while (parent != null)
            {
                var nextFocusElement = parent.FindByName(NextFocusElementName);
                if (nextFocusElement != null)
                {
                    nextFocusElement.Focus();
                    break;
                }
                else
                {
                    parent = parent.Parent;
                }
            }
        }
    }
    

    And then XAML:

    !!! Please let me know if I made a mistake in the code.

提交回复
热议问题