【问题标题】:Focus Entry in a Custom Control自定义控件中的焦点条目
【发布时间】:2021-11-12 22:25:45
【问题描述】:

如何为嵌套在自定义控件中的条目设置焦点?

PackageCode.xaml

<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Name="this"
      
         x:Class="Views.Controls.PackageCode">

<Entry x:Name="txtPackageCode" Completed="txtPackageCode_Completed"> </Entry>

我已经尝试过 txtPackageCode.Focus();

  public PackageCode()
    {
        InitializeComponent();

        txtPackageCode.Focus();

    }

嵌套在我的 Main.xaml 中

 <ContentPage.Content>
    <StackLayout>
        
        <Label Text="Welcome to Xamarin.Forms!"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
                
        <local:PackageCode  ></local:PackageCode>
        

        <Button Text="ClickMe"
                Clicked="Button_Clicked"    ></Button>

    </StackLayout>
   


</ContentPage.Content>

以及如何在我的 Main.xaml 中提取此条目的值?

【问题讨论】:

  • 你需要在你的控件中公开一个页面可以调用的公共方法
  • 我需要什么样的公共方法来关注焦点? OnAppearing 不适用于 ContentView

标签: xamarin xamarin.forms


【解决方案1】:

PackageCode中添加一个公共方法

public void Focus()
{
  txtPackageCode.Focus();
}

然后从Main调用它

public override void OnAppearing()
{
    // you will need to assign an x:Name in the XAML
    packageCode.Focus();
}

【讨论】:

  • 不适用于 Android 或 UWP。
【解决方案2】:
protected override async void OnAppearing()
{
    base.OnAppearing();
    await Task.Delay(1);
    packageCode.SetFocus();
}

这行得通。 Setting the Focus to an Entry in Xamarin.Forms

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 2012-10-22
  • 2014-02-20
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多