1
votes

I have the following Xamarin Forms page that throws an exception on this line...

enter image description here

The first time this page is loaded, the OnAppearing works fine, sets the focus properly, and doesn't throw an exception.

When I navigate back to this page (ie, logout), OnAppearing is throwing the following...

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Xamarin.Forms.Platform.Android.EntryRenderer'.

What is the best way to set focus to a control on a page in Xamarin Forms?

2
why are you calling FindByName? InitializeComponent should generate references to all XAML objects for you.Jason

2 Answers

3
votes

I'm not sure what is in your XAML, but if you define the x:Name="_entry" on the Entry in XAML, and use that name to access the control directly instead of FindByName, it should work fine.

0
votes

I try to reproduce your issue at my side, but it works fine and there is no issue when I click Button to navigate another page and coming back. Please take a look my code:

 <StackLayout>
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="Welcome to Xamarin.Forms!"
            VerticalOptions="CenterAndExpand" />
        <Entry
            x:Name="UserNameentry"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="CenterAndExpand" />
        <Button
            x:Name="btn1"
            Clicked="btn1_Clicked"
            HeightRequest="50"
            HorizontalOptions="FillAndExpand"
            Text="btn1"
            VerticalOptions="CenterAndExpand"
            WidthRequest="200" />
    </StackLayout>

 public Page4()
    {
        InitializeComponent();
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        var usernameentry = FindByName("UserNameentry") as Entry;
        usernameentry.Focus();
    }

    private async void btn1_Clicked(object sender, EventArgs e)
    {
        Page3 page = new Page3();
        await Navigation.PushModalAsync(page);
    }

If you still have this issue, please provide some code about xaml here.