Reputation: 329
I'm running this code when entering a page:
protected override async void OnAppearing()
{
base.OnAppearing();
Title = wasteObject.WasteType;
foreach (var i in wasteDescription)
{
if (i.description_Id == wasteObject.Waste_Id)
{
await viewModel.getDescription(i.wasteImage, i.sortName, i.wasteDescription, myWebView, (error) =>
{
if(error != null)
{
DisplayAlert("Problem", "Not possible", "Ok");
}
});
}
}
}
The issue I'm having is that when I leave that page and get back to it. It has created 2 blocks with text (same text in both blocks). So what I wanna do is to run the code once to prevent more than one block of text to show.
Appreciate all the help, thanks.
Upvotes: 1
Views: 63
Reputation: 2178
As @mjwills said in comment, use boolean field to indicate if the code is already executed. Declare field outside the method OnAppearing
private bool isTextBlockCreated = false;
Then put the code that needs to be run only once in condition check with isTextBlockCreated
if(!isTextBlockCreated)
{
foreach (var i in wasteDescription)
{
if (i.description_Id == wasteObject.Waste_Id)
{
await viewModel.getDescription(i.wasteImage, i.sortName, i.wasteDescription, myWebView, (error) =>
{
if(error != null)
{
DisplayAlert("Problem", "Not possible", "Ok");
}
});
}
}
isTextBlockCreated = true;
}
That should stop running it multiple times.
Upvotes: 3
Reputation: 2617
As @LeRoy said you can run it in the constructor that runs Init which calls viewModel.getDescription() .
protected override async void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if (BindingContext is MyPageViewModel viewModel)
{
foreach (var i in wasteDescription)
{
if (i.description_Id == wasteObject.Waste_Id)
{
await viewModel.getDescription(i.wasteImage, i.sortName, i.wasteDescription, myWebView, (error) =>
{
if(error != null)
{
DisplayAlert("Problem", "Not possible", "Ok");
}
});
}
}
The other way to do it , is that since you have OnAppearing there is also OnDisappearing , and then you can remove the blocks which has been added by the Appearing.
Upvotes: 0