的筆記,重點簡單記就是,ListView 資料來源有變更時,要透過 ObservableCollection 來通知,這樣 ListView 操作時才不會拋出 Exception
Model
namespace ListViewUpdate
{
public class Product
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
public static List<Product> GetData()
{
return new List<Product>
{
new Product() { Name = "楓葉" } ,
new Product() { Name = "樹" } ,
new Product() { Name = "花" } ,
new Product() { Name = "煙火" } ,
new Product() { Name = "夜景" }
};
}
}
}
ViewModelusing System.ComponentModel;
using System.Windows.Input;
using Xamarin.Forms;
// ObservableCollection 所在的 namespace
using System.Collections.ObjectModel;
namespace ListViewUpdate
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// 引發錯誤版本
public List<Product> Source { get; set; }
public ICommand CmdInsert
{
get
{
return new Command(() => Source.Add(new Product() { Name = "植物" }));
}
}
// 可更新版本
public ObservableCollection<Product> UpdatableSource { get; set; }
public ICommand CmdUpdatableInsert
{
// 上課內容是用 List.Insert 插到第一個順位
get
{
return new Command(() => UpdatableSource.Add(new Product() { Name = "植物" }));
}
}
public ViewModel()
{
// 引發錯誤版本
Source = Product.GetData();
// 可更新版本
ObservableCollection<Product> ProdList = new ObservableCollection<Product>();
foreach (var item in Product.GetData())
{
ProdList.Add(item);
}
UpdatableSource = ProdList;
}
}
}