John Livermore
John Livermore

Reputation: 31333

Xamarin Forms: System.ObjectDisposedException when setting Focus to an Entry control

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?

Upvotes: 1

Views: 509

Answers (2)

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10346

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.

Upvotes: 0

Ivan I
Ivan I

Reputation: 9990

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.

Upvotes: 3

Related Questions