c# - 如何在 xamarin 中获得焦点 VisualElement?

标签 c# xamarin.forms focus

我必须在 xamarin 的 CarouselPage 中显示超过 10 个 ContentPage,并且在每个 ContentPage 中有许多标签、按钮、条目。那么我如何才能当前聚焦 VisualElement。

我找到了事件 VisualElement.Focused , VisualElement.Unfocused , VisualElement.FocusChangeRequested .

但没有人能帮助我。

最佳答案

虽然 VisualElementFocusedUnFocused 事件,但并不是所有的控件 将响应,因为事件属于父类(super class)。也是因为平台不同。

例如,WebViewFocusedUnFocused 事件将在 iOS 上有效,但在 Android 上无效。

在您的情况下,LabelButton 在大多数情况下不会调用事件。 Entry 将在编辑模式(输入)时获得焦点,而在结束编辑时失去焦点。

因此,如果您确实想要获取当前获得焦点的元素,您可以在 ContentPage 中定义一个属性。

public object FocusedElement;
private void FocusEvent(object sender, FocusEventArgs e)
{
   FocusedElement = sender; //sender here is the element , like label or entry
}

private void UnfocusEvent(object sender, FocusEventArgs e)
{
   FocusedElement = null;
}

在 xaml 中

定义每个元素的FocusedUnFocused事件

 <Label Text="Welcome to Xamarin.Forms!" 
           HorizontalOptions="Center"
               Focused="FocusEvent" Unfocused="Label_Unfocused"
           VerticalOptions="CenterAndExpand" />


        <Button  Focused="FocusEvent" Unfocused="UnfocusEvent" Text="111"/>

        <Entry   Focused="FocusEvent" Unfocused="UnfocusEvent" HeightRequest="50"  WidthRequest="100" /> 

关于c# - 如何在 xamarin 中获得焦点 VisualElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63133815/

相关文章:

c# - Blazor:IServiceCollection 不包含 AddDefaultIdentity 的定义

c# - 如何对文本框应用约束。在 C# 中,只能将文本框中写入的特定信息/单词添加到列表框中

c# - 当我在接口(interface)方法调用中忘记 `await` 时没有警告

flutter - 如何抑制 Flutter 中的滚动到 View 行为?

android - 我想在谷歌地图中打开我当前的位置

c# - 想要使用 jQuery AJAX 将文本字段值添加到数据库

Xamarin Shell.BackgroundColor 错误

c# - Xamarin 表单 HttpClient GetAsync

java - JLayeredPane。动态改变JPanel的图层索引

c# - Xamarin 5.0 创建启动画面