Case:我希望保持一个元素的焦点,除非试图获取焦点的元素是另一个条目元素。
我有这个组件(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>和(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();
}
}OnLostFocus似乎只得到失去焦点的元素,而没有获得焦点的元素。如何获得当前焦点元素,以便可以看到它是哪种类型的元素?
发布于 2022-09-13 06:29:47
您可以通过迭代根的子视图并调用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是当前页面的父视图。
https://stackoverflow.com/questions/73649236
复制相似问题