How to access in Viewmodel, a Listview q is in a View?

Asked

Viewed 73 times

0

So I have a page called Filmeview on it I have: <ListView BackgroundColor="WhiteSmoke" SeparatorColor="Blue" x:Name="listaFilme"> and I have a Viewmodel class:

 FilmeService filmeService = new FilmeService(); 
 var lista = filmeService.GetAll().Result;
 // (quero usar a propriedade x:Name do list view nessa classe)

But when I’m gonna put listaFilme.itemsSource it cannot link this Listview q came from Filmeview, my question is how I link the View class in my view model to access this Listview to show the data?

  • This link is made recommendably through a standard called MVVM with the Binding features that the Xamarin has native. Check the first steps in the official documentation that will help you. Your question is very broad, difficult to help,.

1 answer

1


Hello @Guilherme Petena!

Although this is not a practice recommended by Microsoft when building apps using Xamarin(see documentation to learn more)

You get what you’re talking through in the following way:

Assuming your View is called MinhaView in your constructor I do the Binding of viewModel and at the same time step to viewModel which will be called MinhaViewModel the page reference that is linked.

Done this the Viewmodel will have the reference to the page that now just useful the method FindByName of the same to obtain control of the same.

as can be seen below:

public class MinhaViewModel {

    private Page _paginaRelacionada;

    public MinhaViewModel(Page paginaRelacionada){
        _paginaRelacionada = paginaRelacionada;
    }

    public bool TentarObterElementoDaPagina(string elementName, object elementoProcurado){
       elementoProcurado = _paginaRelacionada?.FindByName(elementName);
       return elementoProcurado != null;        
    }
}


public partial class MinhaView {

    public MinhaView() {

     var viewModel = new MinhaViewModel(this);
     BindingContext = viewModel;

    }


}

obs. This technique does not work for controls that are within a template, for example, in the case of a listview item template

Browser other questions tagged

You are not signed in. Login or sign up in order to post.