Update ListView after Return with PopAsync in Xamarin Forms
How to update ListView
after returning to View
using PopAsync
?
I need ListView
to load her items after the address insert View writes a new address.
Note: the PushAsync
or PushModalAsync
return to View
correctly, but wrong for what I need.
Insertirenderecoviewmodel:
if (Api.APICliente.InserirEndereco(objEnd) == 0)
{
if (alteracao == false)
{
await Page.DisplayAlert("Mensagem", "Endereço inserido com sucesso!", "OK");
}
else
await Page.DisplayAlert("Mensagem", "Endereço alterado com sucesso!", "OK");
}
else
await Page.DisplayAlert("Alerta", "Não foi possível inserir os dados!", "OK");
// Aqui retorna para a View de MeusEndereços onde contem a ListView que irá carregar os endereços cadastrados.
await Page.Navigation.PopAsync();
4 answers
In your view of myaddresses
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = new suaViewModel();
}
To populate a ListView in Xamarin.Forms it is always recommended to use an ObservableCollection because it notifies you of any changes to the collection (insert,delete,update). Good with an ObservableColection in the ListView ItemSource using the MVVM pattern your ListView Page has an event called Appearing you can call your ViewModel's method that populates the listview data in this event. Example:
public partial class Page : ContentPage
{
private PageViewModel vm;
public Page()
{
InitializeComponent();
vm = new PageViewModel(this.Navigation);
this.BindingContext = vm;
this.Appearing += TennisClubMessagePage_Appearing;
}
private void TennisClubMessagePage_Appearing(object sender, System.EventArgs e)
{
vm.LoadDataAsync();
}
}
Overwrite the OnAppearing method of your view.
For example:
protected override void OnAppearing()
{
base.OnAppearing();
lstParceiro.SelectedItem = null;
AtualizarLista();
}
In this case I delegated to a method (Updatelist) the task of updating the ItemsSource from my list.
Create one event handler
in viewmodel
, and another in view
,
when calling the form, whether modal or not.
On form
calling form modal
, make the following call:
var modalform = new seumodalform();
modalform.seuviewhandler += async(O,e)=>{ o valr que voce quer atualizar = O;}
In the constructor of view
just define:
seuVM.seuVMHandler = seuViewHandler;
//E na rotina que fechar o view, se for realizado via mvvm
seuVMhandler?.invoke(objeto, args);
//Se for feito via codebehind da view, basta fazer o mesmo invoke
seuViewhandler?.invoke(objeto, args);