ListView ItemSource Binding in async function is not working in Xamarin forms

I am working on a cross platform xamarin forms application(with MVVM). In this application i am trying to bind a observable collection to ItemSource of ListView. i am writing a async function to get the values from rest service. When i assign those values then those values are not bound to listview. I have INotifyPropertyChanged implementation in BaseViewModel class.

My Observation:
When i add some objects to collection outside async function then those values are bound to listview but when i do same in async function. I know that using async will create a new background thread and as this code is not running on main thread the assignment might have some issue. To resolve this i used device.begininvokeonmainthread to force only assignment to run on main thread. But none of the solutions are working for me.

Please provide me if you have any working example in.

Best Answer

  • VeereshAngadiVeereshAngadi ✭✭ US ✭✭
    Accepted Answer
    I solved this issue. I was using compiler service in my property changed method of base view model. Thank you all for your responses.

Answers

  • SreeeeSreeee ✭✭✭✭✭ INMember ✭✭✭✭✭
    edited December 2017

    Are you calling the async method from the viewmodel constructor?

  • VeereshAngadiVeereshAngadi ✭✭ USMember ✭✭

    No i am calling it in Button click method

  • VeereshAngadiVeereshAngadi ✭✭ USMember ✭✭

    I am attaching view and viewmodel text files for your reference.

    this is my sample application. Now i am just trying to add items to my collection in button click method and i am able to reproduce the problem i am facing

  • shubham1shubham1 ✭✭✭ Member ✭✭✭
    edited January 2018

    Device.BeginInvokeOnMainThread(() =>
    {
    listview.ItemsSource = setData;
    });

    try this...

  • shubham1shubham1 ✭✭✭ Member ✭✭✭

    ... ...

  • shubham1shubham1 ✭✭✭ Member ✭✭✭
    edited January 2018

    @VeereshAngadi said:
    I am attaching view and viewmodel text files for your reference.

    this is my sample application. Now i am just trying to add items to my collection in button click method and i am able to reproduce the problem i am facing

    < Button x:name="btnload" Text="Load" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"
    Command="{Binding LoadCommand}" /> ... ...

  • VeereshAngadiVeereshAngadi ✭✭ USMember ✭✭
    Accepted Answer
    I solved this issue. I was using compiler service in my property changed method of base view model. Thank you all for your responses.
Sign In or Register to comment.