我有一个分组的ListView。添加新项目时,ListView的内容不会更新。我该如何解决?这是我的代码:
练习课:
let localizedJSONObject = try LocalizedJSONObject(json)
用于分组项目的类:
public class Exercise : INotifyPropertyChanged
{
public enum muscleGroups
{
None,
Back,
Chest
}
public Exercise() { }
private string title { get; set; }
private muscleGroups muscleGroup { get; set; }
public string Title
{
get { return title; }
set
{
if (title != value)
{
title = value;
OnPropertyChanged("Title");
}
}
}
public muscleGroups MuscleGroup
{
get { return muscleGroup; }
set
{
if (muscleGroup != value)
{
muscleGroup = value;
OnPropertyChanged("MuscleGroup");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
将分组项添加到ListView(名称exerciseList)中,按MuscleGroup属性的值进行分组:
public class ExerciseGrouping<K, T> : ObservableCollection<T>
{
public K Name { get; private set; }
public ExerciseGrouping(K name, IEnumerable<T> items)
{
Name = name;
foreach (T item in items)
Items.Add(item);
}
}
添加新项目时,如何更新ListView的内容? 提前谢谢。
添加新项目的代码(我有另一页练习页面来编辑或添加新项目):
Exercises = new ObservableCollection<Exercise>
{
new Exercise {Title="Exercise 1", MuscleGroup = Exercise.muscleGroups.Chest},
new Exercise {Title="Exercise 2", MuscleGroup = Exercise.muscleGroups.Chest},
new Exercise {Title="Exercise 3", MuscleGroup = Exercise.muscleGroups.Back},
new Exercise {Title="Exercise 4", MuscleGroup = Exercise.muscleGroups.Back}
};
var groups = Exercises.GroupBy(p => p.MuscleGroup).Select(g => new ExerciseGrouping<Exercise.muscleGroups, Exercise>(g.Key, g));
ExerciseGroups = new ObservableCollection<ExerciseGrouping<Exercise.muscleGroups, Exercise>>(groups);
//exercisesList.BindingContext = Exercises;
exercisesList.BindingContext = ExerciseGroups;