条目FindByName在xamarin形式mvvm中始终为null

时间:2019-01-08 13:28:11

标签: xamarin mvvm xamarin.forms

我有一个按钮 我想将重点放在按钮单击上 所以我的按钮命令是:

public Command FocusPassword
        {
            get
            {
                return new Command(() =>
                {
                    Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
                    passwordEntry.Focus();
                });
            }
        }

myEntry总是返回null,那么如何解决呢?

3 个答案:

答案 0 :(得分:1)

我只是解决了这个问题:

Page currentPage = Navigation.NavigationStack.LastOrDefault();
                    Entry passwordEntry = currentPage.FindByName<Entry>("PassEntry");
                    passwordEntry.Focus();

答案 1 :(得分:0)

myEntry为空,还是passwordEntry?您正在将返回的对象分配给myEntry,然后尝试将焦点放在passwordEntry上:

Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
passwordEntry.Focus();

是的,请确保Entry的{​​{1}}设置为x:Name,例如:

pEntry

答案 2 :(得分:0)

您也可以尝试使用我的演示。 enter image description here

MainPage.xaml(不要忘记BindingContext)

<?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:EntryDemo"
         x:Class="EntryDemo.MainPage">

<StackLayout>

    <Grid Margin="10">
     <Grid.BindingContext>
            <local:BindingViewModel/>
     </Grid.BindingContext>

     <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
     </Grid.RowDefinitions>
     <Entry 
        Grid.Row="0"
        HorizontalOptions="CenterAndExpand"
        Text="account"
        x:Name="accountEntry"
         />
    <Entry 
        Text="password"
        Grid.Row="1"
        HorizontalOptions="CenterAndExpand"
        x:Name="pEntry"
     />
    <Button
        Grid.Row="2"
        HorizontalOptions="CenterAndExpand"
        x:Name="MyButton"
        Text="FocusEntry "
        Command="{Binding FocusCommand}"
        />
    </Grid>
</StackLayout>

</ContentPage>

您应该在execute方法中运行FindByName BindingViewModel.cs

 public class BindingViewModel: BindableObject
{
    public BindingViewModel()
    {

        FocusCommand = new Command(
            execute: () =>
            {
                Entry accountEntry = Application.Current.MainPage.FindByName<Entry>("accountEntry");
                Entry myEntry = Application.Current.MainPage.FindByName<Entry>("pEntry");
                accountEntry.Focus();

            }
     );

    }
    public ICommand FocusCommand { private set; get; }
}