Ryan
Ryan

Reputation: 3982

Why is the Binding ItemSource property not found on my ViewModel?

I have Xamarin Forms app to show a deck of cards. The Deck is initialized with a static collection in the App class. (A breakpoint shows it is populated). The MainPage has a MainPageViewModel set as the BindingContext:

Public MainPage(){
    InitilizeComponent();
    BindingContext = new MainPageViewModel()
}

The MainPageViewModel has a simple property to retrieve the populated Deck.Cards:

public static IEnumerable<Card> Cards { get { return Deck.Cards; }}

This is used in a Carousel collection in the main page.

However, the view is empty! I see

`[0: ] Binding: 'Cards' property not found on 'mypackage.ViewModels.MainPageViewModel', target property 'Xamarin.Forms.CarouselView.ItemsSource'

Why is the property not found? It is public and IEnumerable.

Upvotes: 0

Views: 1046

Answers (2)

javachipper
javachipper

Reputation: 537

Change this:

public static IEnumerable<Card> Cards { get { return Deck.Cards; }}

to this:

public ObservableCollection<Card> Cards{ get {return new ObservableCollection<Card>(Deck.Cards.ToList()); }}

Hope this helps.

Upvotes: 1

DavidS
DavidS

Reputation: 2944

Assuming that your Xaml currently has ItemsSource={Binding Cards}, then make Cards non-static and it'll work.

If you want to keep Cards a static property, use x:Static:

ItemsSource={x:Static vm:MainPageViewModel.Cards}

And make sure you declare the namespace: xmlns:vm="clr-namespace:mypackage.ViewModels" at the top of your Xaml file.

Upvotes: 1

Related Questions