Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Populating an observable collection in a ViewModel-Just learning MVVM

$
0
0

Hello,
I am still learning Xamarin and I have successfully populated a ListView with an Observable collection from a sqlite DB, but only in code behind like this:

ObservableCollection<userTbl> userInfo = new ObservableCollection<userTbl>(await App.Database.GetUserAsync());
usrLst.ItemsSource = userInfo;

I now want to do this in the VM. One, because I may want this OC somewhere else in my app and Two, because this allows me to not only put it in a ListView, but maybe in some other controls. Three, I want to learn the MVVM method
This is what I have tried:

        private ObservableCollection<userTbl> _userInfo=new ObservableCollection<userTbl>(await App.Database.GetUserAsync());

        public ObservableCollection<userTbl> userInfo
                {
                    get
                    {

                        //_userInfo = App.Database.GetUserAsync(); I have also tried this instead of setting it at the declaration
                        return _userInfo;

                    }
                    set
                    {
                        _userInfo = value;
                        OnPropertyChanged();

                    }
                }

From what I have read, this should populate userInfo because I am setting it and returning it. This should in turn allow me bind it to my listView. However, I am getting an error about not being able to convert a task to an observable collection. I think that this is because in my data access layer the data call is:

public Task<List<userTbl>> GetUserAsync()
        {
            return _database.Table<userTbl>().ToListAsync();
        }

and there is a mismatch in the way that it is calling the data vs the way that the VM wants to receive it. The connection is a SQLiteAsyncConnection.
Here are my questions:
Should I make a new data call in my data class that does not use an async connection?
Should I create an async function in the VM to populate an observable collection and then assign it to _userTbl in the GET method? (I have seen examples of this by iterating through the list and literally populating am OC; but this seems like it creates more work for the App because it has to populate one list and then assign those values when my data call already creates a list.
Am I going about this all wrong and is there a better way?
Thank you,
Rob Durrance


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>