Reputation: 443
I have a button and i want to focus an entry on button click so my button command is:
public Command FocusPassword
{
get
{
return new Command(() =>
{
Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
passwordEntry.Focus();
});
}
}
myEntry always returning null,so how to solve this?
Upvotes: 0
Views: 1797
Reputation: 443
I simply solve this:
Page currentPage = Navigation.NavigationStack.LastOrDefault();
Entry passwordEntry = currentPage.FindByName<Entry>("PassEntry");
passwordEntry.Focus();
Upvotes: 2
Reputation: 9234
You could try to use my demo as well.
MainPage.xaml
(Do not forget to 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>
You should run FindByName
in execute method
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; }
}
Upvotes: 0
Reputation: 6098
Is it myEntry
that is null, or passwordEntry
? You are assigning the returned object to myEntry
but then trying to set the focus on passwordEntry
:
Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
passwordEntry.Focus();
And yes, make sure that the Entry
does have the x:Name
set to pEntry
, e.g.:
<Entry x:Name="pEntry" ... />
Upvotes: 0