【问题标题】:How to set focus for an Entry in Xamarin.Forms targeting UWP platform?如何为针对 UWP 平台的 Xamarin.Forms 中的条目设置焦点?
【发布时间】:2017-07-15 06:34:58
【问题描述】:

我创建了一个使用Xamarin.Forms 定位AndroidUWP 平台的应用程序。 (桌面上的 UWP,而不是手机)。
我正在使用主/详细信息导航,当从一个页面导航到另一个页面时,它在 UWP 上保持打开状态。在主页上,只有在 UWP 上,我有一个 Entry,当视图出现时我想聚焦,所以我这样做了:

protected override void ViewIsAppearing(object sender, EventArgs e)
{
    base.ViewIsAppearing(sender, e);
    Device.OnPlatform(WinPhone: () =>
    {
        CustomComponent.GainFocus();
    });
}

在我的 CustomComponent 实际上是 StackLayout 里面,我有这个:

public void GainFocus()
{
    CustomEntry.Focus();
}

我的问题是,例如当我导航到 Page2Page3 并返回 MainPage 时,该函数被调用,但该条目从未被聚焦,焦点停留在导航面板上从导航列表中单击的项目。 如何解决此问题,以便我的 Entry 始终获得焦点?

编辑:

我已经进行了一些调试以了解发生了什么。
我将FocusedUnfocused 的处理程序添加到我的CustomEntry

private void CustomEntry_Unfocused(object sender, FocusEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("CustomEntry_Unfocused");
}

private void CustomEntry_Focused(object sender, FocusEventArgs focusEventArgs)
{
    System.Diagnostics.Debug.WriteLine("CustomEntry_Focused");
}

添加此内容后,我运行了我的应用程序并检查了输出。
ViewIsAppearing > Calls Focused。
在条目外单击 > 调用未聚焦
从主页导航到另一个 > 不调用 Unfocused,然后返回主页 > 不调用 Focused
如果CustomEntry 没有聚焦,我离开主页并返回 > 聚焦呼叫。

编辑2:

我尝试以这种方式在 OnViewIsDisappearing 事件中强制 Unfocus

protected override void ViewIsDisappearing(object sender, EventArgs e)
{
    base.ViewIsDisappearing(sender, e);
    Device.OnPlatform(WinPhone: () =>
    {
        CustomComponent.LoseFocus();
    });
}

在自定义组件内部:

public void LoseFocus()
{
    CustomEntry.Unfocus();
}

尝试此操作后,它也不会调用Unfocused..
有什么想法吗?

【问题讨论】:

    标签: uwp xamarin.forms focus master-detail xamarin.forms.entry


    【解决方案1】:

    只需添加

    CustomEntry.Focus();

    在您想要的页面的InitializeComponent(); 之后。

    【讨论】:

    • 这是一个简单的解决方法,Karan 是对的,我会给他一个赞成票,很遗憾看到一个反对票只是因为它通常是一个简单的答案。
    猜你喜欢
    • 2015-09-19
    • 2021-11-16
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多