How do you find the newly focused element in .net-maui (used inside unfocused event handler)

Viewed 67

Case: I want to keep an element focused unless the element that tries to grab focus is a another Entry element.

I have this component (SearchBar.xaml)

    <?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:localization="clr-namespace:POS365.Src.Extensions"
             xmlns:fontAwesome="clr-namespace:FontAwesome"
             x:Class="SomeApp.Src.Components.SearchBar">
    <Grid ColumnDefinitions="32,*">
        <Label Grid.Column="0" FontFamily="FAS" Text="{x:Static fontAwesome:FontAwesomeIcons.MagnifyingGlass}" FontSize="Large" Style="{DynamicResource HeaderBarSearchIconStyle}"/>
        <Entry Grid.Column="1" x:Name="SearchField" MaxLength="20" Text="" HeightRequest="32" />
    </Grid>
</ContentView>

and (SearchBar.xaml.cs)

using System.ComponentModel;

namespace SomeApp.Src.Components;

public partial class SearchBar : ContentView
{
    public SearchBar()
    {
        InitializeComponent();
        SearchField.Unfocused += OnLostFocus;
    }

    public void OnLostFocus(object sender, FocusEventArgs e)
    {
        // TODO: Find out when to focus this, probably based on what takes focus if possible
        // FocusSearchField();
    }

    // Used by Loaded event elsewhere
    public void FocusSearchField()
    {
        SearchField.Focus();
    }   
}

It seems that OnLostFocus only gets the element that lost focus and not the element that took focus. How do I get the current focused element, so I can see which type of element it is?

1 Answers

You can determine this by iterating through root's child view and calling the view.IsFocused method.

var views = rootLayout.Children; 

    foreach (View view in views)
    {
        if (view != null && view.IsFocused)
        {

            System.Diagnostics.Debug.WriteLine("view focused is : " + view);
        }

    }

Note:

rootLayout is the parent view of current page.

Related