FindByName适用于第一个条目,但第二个条目返回null ...?

时间:2017-12-16 12:28:09

标签: xaml xamarin f# xamarin.forms

我对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

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

1 个答案:

答案 0 :(得分:1)

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

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