【问题标题】:FindByName works for the first entry, but returns null for the second...?FindByName 适用于第一个条目,但返回 null 为第二个......?
【发布时间】:2017-12-16 12:28:09
【问题描述】:

我对 Xamarin.Forms 的这种行为感到非常困惑。我有这个页面:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:GW.Frontend.XF"
             x:Class="GW.Frontend.XF.AppPage">
    <StackLayout x:Name="mainLayout" Padding="20,20,20,20">
        <Label Text="Welcome to GW" x:Name="welcomeLabel"
               VerticalOptions="Center" HorizontalOptions="Center" />

        <Entry x:Name="passphraseEntry" IsPassword="true"
               Placeholder="Input your new pass-phrase:"
               TextChanged="OnPassphraseTextChanged" />
        <Entry x:Name="passphraseEntryConfirmation" IsPassword="true"
               Placeholder="Repeat your passphrase here"
               TextChanged="OnPassphraseTextChanged" />
        <Button x:Name="createButton"
                Text="Create my accounts" IsEnabled="false"
                HorizontalOptions="Center"
                Clicked="OnCreateButtonClicked" />
    </StackLayout>
</ContentPage>

这是 AppPage.xaml.fs 中的代码:

namespace GW.Frontend.XF

open System

open Xamarin.Forms
open Xamarin.Forms.Xaml

type AppPage() =
    inherit ContentPage()
    let _ = base.LoadFromXaml(typeof<AppPage>)
    let mainLayout = base.FindByName<StackLayout>("mainLayout")
    let passphrase = mainLayout.FindByName<Entry>("passphraseEntry")
    let passphraseConfirmation = mainLayout.FindByName<Entry>("passphraseEntryConfirmation")
    let createButton = mainLayout.FindByName<Button>("createButton")

    member this.OnCreateButtonClicked(sender: Object, args: EventArgs) =
        ()

    member this.OnPassphraseTextChanged(sender: Object, args: EventArgs) =
        Console.WriteLine("______________________A")
        if (passphrase.Text.Length > 0) then

            Console.WriteLine("______________________B")
            if (passphraseConfirmation.Text.Length > 0) then

                Console.WriteLine("______________________C")
                createButton.IsEnabled <- true

令人惊讶的是,passphrase 不为空(因为 ___B 打印在控制台中)但 passphraseConfirmation 为空! (所以它会抛出 NullReferenceException。)这怎么可能?我希望 FindByName 在所有情况下都有效,不仅适用于 StackLayout 容器中的第一个元素。

【问题讨论】:

    标签: xaml xamarin f# xamarin.forms


    【解决方案1】:

    我的错,不是passphraseConfirmation 为空,而是它的Text 属性为空! (显然是因为如果它没有在 XAML 中设置并且用户还没有在上面输入任何内容,那么它可能仍然保持为空。)

    我会留下问题而不是删除它,以防有人从 Entry 小部件的工作方式中忽略了这个愚蠢的假设。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2020-03-18
      相关资源
      最近更新 更多