I've a CollectionView inside my Page and a label Name binding with class
<CollectionView Grid.Column="0"
Grid.Row="1"
SelectionMode="Single"
ItemsSource="{Binding MarketplacePackages}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Name}" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
then i've a class Marketplace
public class MarketplacePackage
{
public string Name { get; set; }
}
and inside my ViewModel i've that
a listView
List<MarketplacePackage> marketplacePackages;
public List<MarketplacePackage> MarketplacePackages
{
get { return marketplacePackages; }
set { SetProperty(ref marketplacePackages, value); }
}
a constructor where i initialize the list
public MarketplaceViewModel()
{
Catalogue = new Command(onCatalogueClicked);
MyDevice = new Command(onMyDeviceClicked);
MyOrders = new Command(onMyOrderdsClicked);
MarketplacePackages = new List<MarketplacePackage>() {
new MarketplacePackage()
{
Name = catalogueList[0],
},
new MarketplacePackage()
{
Name = catalogueList[1]
},
new MarketplacePackage()
{
Name = catalogueList[2]
},
new MarketplacePackage()
{
Name = catalogueList[3]
}
};
//this works!
//MarketplacePackages[0].Name = "String";
}
and when i call onClickMethod i try to change the data inside my listView
private async void onCatalogueClicked()
{
MarketplacePackages[0].Name = "String";
}
Your MarketplacePackage
class has to implement the INotifyPropertyChanged
interface (or to inherit from ObservableObject
if you're using XamarinCommunityToolkit or MvvmHelpers) and notify when the Name
property is changed.
e.g.:
public class MarketplacePackage : ObservableObject
{
string name;
public string Name { get => name; set => SetProperty(ref name, value); }
}
It works when you set/change the Name
property in the constructor of the ViewModel because the View reads the initial values after the constructor is finished.