用例:我想让一个元素保持焦点,除非试图获取焦点的元素是另一个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似乎只得到失去焦点的元素,而没有得到获得焦点的元素。我如何得到当前获得焦点的元素,这样我就可以看到它是哪种类型的元素?
1条答案
按热度按时间rjjhvcjd1#
您可以通过遍历root的子视图并调用
view.IsFocused
方法来确定这一点。注意事项:
rootLayout
是当前页面的父视图。