As Jason said, you need to implement INotifyPropertyChanged interface for Item class if you want to change Item property firstly.
public class Item:ViewModelBase
{
private string _Title;
public string Title
{
get { return _Title; }
set
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
The ViewModelBase is the class that implementing INotifyPropertyChanged interface.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Then I suggest you can use ObservableCollection to replace List, because Observablecollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Finally, using binding for ListView and change selecteditem property.
<StackLayout>
<ListView x:Name="listview1" ItemsSource="{Binding source}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Title}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button
x:Name="btn1"
Clicked="btn1_Clicked"
Text="update data" />
</StackLayout>
public partial class Page18 : ContentPage
{
public ObservableCollection<Item> source { get; set; }
public Page18()
{
InitializeComponent();
source = new ObservableCollection<Item>()
{
new Item(){Title="title 1"},
new Item(){Title="title 2"},
new Item(){Title="title 3"},
new Item(){Title="title 4"},
new Item(){Title="title 5"}
};
this.BindingContext = this;
}
private void btn1_Clicked(object sender, EventArgs e)
{
Item item = listview1.SelectedItem as Item;
item.Title = "Changed title";
}
}
About Binding and INotifyPropertyChanged, please take a look:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm
INotifyPropertyChanged
? – cahyo