Reputation: 157
I have these view:
<StackLayout Orientation="Vertical" Padding="30,24,30,24" Spacing="10">
<syncfusion:SfListView x:Name="listView" ItemsSource="{Binding Items}">
<syncfusion:SfListView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Text}"/>
</StackLayout>
</DataTemplate>
</syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
And it's C# code:
public partial class ItemsPage : ContentPage
{
ItemsViewModel _viewModel;
public ItemsPage()
{
InitializeComponent();
BindingContext = _viewModel = new ItemsViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.OnAppearing();
}
}
Here the model:
public class Item
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
I'm not sure why but with this view model:
public class ItemsViewModel : BaseViewModel
{
private Item _selectedItem;
public ObservableCollection<Item> Items { get; }
public Command LoadItemsCommand { get; }
public Command AddItemCommand { get; }
public Command<Item> ItemTapped { get; }
public ItemsViewModel()
{
Title = "Contacts by David Zomada";
Items = new ObservableCollection<Item>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
ItemTapped = new Command<Item>(OnItemSelected);
AddItemCommand = new Command(OnAddItem);
}
async Task ExecuteLoadItemsCommand()
{
IsBusy = true;
try
{
Items.Clear();
var items = await DataStore.GetItemsAsync(true);
foreach (var item in items)
{
Items.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
public void OnAppearing()
{
IsBusy = true;
SelectedItem = null;
}
public Item SelectedItem
{
get => _selectedItem;
set
{
SetProperty(ref _selectedItem, value);
OnItemSelected(value);
}
}
private async void OnAddItem(object obj)
{
await Shell.Current.GoToAsync(nameof(NewItemPage));
}
async void OnItemSelected(Item item)
{
if (item == null)
return;
// This will push the ItemDetailPage onto the navigation stack
await Shell.Current.GoToAsync($"{nameof(ItemDetailPage)}?{nameof(ItemDetailViewModel.ItemId)}={item.Id}");
}
}
The compiler says: "Binding: Property "Text" not found on "Contacts.ViewModels.ItemsViewModel". (XFC0045)"
I'm clearly wrong but I don't get it where is my mistake? Could you help me to understand why my view is not binding correctly to the view model?
My understanding so far is that, if you bind an items source to a collection view when you use the binding to bind a property on a data template, the data get it's data from the items source.
Upvotes: 1
Views: 906
Reputation: 157
I was using this property on the view:
x:DataType="local:ItemsViewModel"
It makes the compiler understand that it should find the property 'Text' on the view model, not on the model...
More info here: Xamarin.Forms Compiled Bindings
Upvotes: 1