Observablecollection is not populating

Asked

Viewed 28 times

-1

I want to popular an Observablecollection to later display when the screen is loaded. Inside my Viewmodel I am setting the data for test, but when I print it has no content.

I run Noticeshow() when the page / Contentpage is loaded.

    protected override void OnAppearing()
    {
        base.OnAppearing();

        ChannelViewModel ViewModel = new ChannelViewModel();
        ViewModel.NoticeShow();   
    }

Inside of my Viewmodel

    public class Notice
    {
        public string NoticeMessage { get; set; }
    }

    private ObservableCollection<Notice> Notices; 

    public void NoticeShow()
    {
        Notices = new ObservableCollection<Notice>()
        {
            new Notice { NoticeMessage = "Teste de mensagem 1" },
            new Notice { NoticeMessage = "Teste de mensagem 2" },
            new Notice { NoticeMessage = "Teste de mensagem 3" }
        };

        Console.WriteLine("Console log -> "+Notices);                        
    }

Return of the writeline Console

Console log -> System.Collections.ObjectModel.ObservableCollection`1[iSequi.ViewModels.ChannelViewModel+Notice]

1 answer

1


Hi @RRV

In your View constructor you must set Bindingcontext to your Viewmodel:

public partial class MinhaView{
   public MinhaView(){
     ChannelViewModel ViewModel = new ChannelViewModel();
     BindingContext = ViewModel;
   }
}

Then in the event Appering, you can use your code:

protected override void OnAppearing()
{
    base.OnAppearing();
    ViewModel.NoticeShow();   
}

Next you should perform the Notices in your View, just remembering to set the property Notices present in Viewmodel as public rather than private:

public ObservableCollection<Notice> Notices; 

Browser other questions tagged

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