XAML 如何在.net-maui中找到新获得焦点的元素(在未获得焦点的事件处理程序中使用)

wlp8pajw  于 2022-12-07  发布在  .NET
关注(0)|答案(1)|浏览(326)

用例:我想让一个元素保持焦点,除非试图获取焦点的元素是另一个Entry元素。
我有这个组件(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>

和(搜寻列. 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();
    }   
}

OnLostFocus似乎只得到失去焦点的元素,而没有得到获得焦点的元素。我如何得到当前获得焦点的元素,这样我就可以看到它是哪种类型的元素?

rjjhvcjd

rjjhvcjd1#

您可以通过遍历root的子视图并调用view.IsFocused方法来确定这一点。

var views = rootLayout.Children; 

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

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

    }

注意事项:
rootLayout是当前页面的父视图。

相关问题