Reputation: 3592
I want to bind a listview to my viewmodel but I get ArgumentNullException
.
I use xamarin.forms and the exception appears in android and ios projects but not in uwp.
Itemsource returns an exception when I use binding with the viewmodel. When i don't use binding in my xaml the exception disappears.
System.ArgumentNullException has been thrown
Value cannot be null.
Parameter name: element
ViewModel
private ObservableCollection<T> pages = new ObservableCollection<T>();
public ObservableCollection<T> Pages
{
get { return pages; }
set
{
pages = value;
OnPropertyChanged("Pages");
}
}
VM Constructor
public ViewModel()
{
_service = new Service();
someitems = _service.getitems();
Pages = new ObservableCollection<T>(someitems);;
}
Service
return new ObservableCollection<T>(items);
View
ItemsSource="{Binding Pages}"
The problem seems to be the setter pages = value;
What is wrong?
Upvotes: 0
Views: 944
Reputation: 3592
I changed my service to an async
data source and finally I used:
Constructor
public ViewModel()
{
InitPages();
}
Async Init()
private async void Init()
{
Pages = await ServiceFunction();
}
Upvotes: 0
Reputation: 9356
Based on the code posted it seems you are trying to initialize the Pages collection with null value.
public ViewModel()
{
Pages = new ObservableCollection<T>(someitems);;
}
In your ViewModel constructor someitems
seems to be null. I assume this since you are using Generics
and at that moment you probably don't know the type is gonna be used.
If you want/need to initialize it with a value you can do it passing a parameter in the ViewModel constructor:
public ViewModel(IList<T> someitems)
{
Pages = new ObservableCollection<T>(someitems);
}
Note: You don't need to create a backing field when working ObservableCollection
, with an Auto-Property would be enough, but be advised that using this you must keep the same instance and when replacing objects you will do it clearing Clear()
and adding Add()
the new items.
public ObservableCollection<T> Pages { get; set; }
Hope this helps!
Upvotes: 2