Hello,
How can a ListView be updated when an item in the bound ObservableCollection is modified while using the MVVM .NET Community Toolkit?The ListView's ItemsSource property is bound to an ObservableCollection, and the ViewModel inherits from the ObservableObject class.
Firstly, if you want to updated the chiled item in the ObservableCollection, your Model inherits from the ObservableObject class as well like following code.
public partial class Person: ObservableObject
{
[ObservableProperty]
private string? name;
[ObservableProperty]
private int? age;
}
Then I use RelayCommand
in the ViewModel to test the Update Function, I Update the first item value in the ObservableCollection in the ChangeCommand.
public partial class MainViewModel: ObservableObject
{
[RelayCommand]
private void Change()
{
// Update the first item value in the ObservableCollection
Persons[0].Age = 50;
Persons[0].Name = "Item 50";
//remove the item
//Persons.RemoveAt(0);
//add the itme
// Persons.Add(new Person { Name = "Item 3", Age = 30 });
}
public ObservableCollection<Person> Persons { get; } = new ObservableCollection<Person>();
public MainViewModel()
{
//init the data in the ObservableCollection
Persons.Add(new Person { Name = "Item 1", Age = 10 });
Persons.Add(new Person { Name = "Item 2", Age = 20 });
}
}
Here is my tested layout, when I click the change Button that bind the ChangeCommand, It will execute change method in the viewModel.
<ContentPage.BindingContext>
<local:MainViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<Button Text="change" Command="{Binding ChangeCommand}"></Button>
<ListView ItemsSource="{Binding Persons}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Person">
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Label Text="{Binding Age}" Margin="10,0,0,0"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.