Home > Mobile >  Can a ContentView receive focus?
Can a ContentView receive focus?

Time:02-25

I have an element that I want to become highlighted when navigated to with a D-pad and respond to an "enter" button. I assumed I could do this with a focused element and am trying to set up my ContentView to handle such interaction.

The ContentView class inherits from VisualElement and has a Focus() method. The documentation states that for the Focus() method to work, the "[element] must be able to receive focus."

How can I make an element "able to receive focus"? It doesn't appear to work in UWP or Tizen with this bare-bones example. Tabbing, clicking, arrow keys, programmatically setting the focus... Nothing sets IsFocused to true, and my callback is never called.

using System;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MyProject.Components
{
    public class FocusMe : ContentView
    {
        public FocusMe ()
        {
            Content = new StackLayout {
                Children = {
                    new Label { Text = "Welcome to Xamarin.Forms!" }
                }
            };
            Focused  = FocusMe_Focused;
            Task.Run(async () => {
                await Task.Delay(5000);
                Focus(); // false
                _ = IsFocused; // false
            });
        }

        private void FocusMe_Focused(object sender, FocusEventArgs e)
        {
            // never called
        }
    }
}

CodePudding user response:

Can a ContentView receive focus?

Base on the testing, ContentView will not receive Focused event. However, Frame layout could receive focused event, and frame inherits from ContentView, you could use Frame to replace. Please note, you need to place focusable control in it such as button.

  • Related