Hello,
Welcome to our Microsoft Q&A platform!
Hi, @bilel miled To update the ListView
automatically when new items are added, besides using an ObservableCollection
, the model class also needs to implement the INotifyPropertyChanged
interface to raise the PropertyChanged event.
Try to set data binding using MVVM pattern to update the data at runtime, check the code:
public partial class TestPage : ContentPage
{
TestViewModel viewModel;
public TestPage()
{
InitializeComponent();
viewModel = new TestViewModel();
BindingContext = viewModel;
}
}
public class TestModel : INotifyPropertyChanged
{
private string theContent;
public string TheContent
{
get
{
return theContent;
}
set
{
if (theContent != value)
{
theContent = value;
NotifyPropertyChanged("TheContent");
}
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class TestViewModel
{
public ObservableCollection<TestModel> ContentCollection { get; set; }
public TestViewModel()
{
ContentCollection = new ObservableCollection<TestModel>();
//add the data
}
}
Set data binding for the listView in xaml
<ListView x:Name="listview" ItemsSource="{Binding DataCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding TheContent}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Related doc: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
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.