这是我的代码:
public partial class MyGS: ContentPage {
public MyGS() {
InitializeComponent();
BindingContext = new MyGSViewModel();
}
public class MyGSViewModel: INotifyCollectionChanged {
public event NotifyCollectionChangedEventHandler CollectionChanged;
public ObservableCollection < SchItem > Items {get;private set;}
public MyGSViewModel() {
Items = new ObservableCollection<SchItem>();
//Item Population
public void removeItem(int rid, int lid) {
SchItem myItem = Items[lid];
Items.Remove(myItem);
CollectionChanged ? .Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, myItem));
}
}
public class SchItem {
public int realm_id {get;set;}
public int list_id {get;set;}
public ICommand TapCommand {
get {return new Command(() => {
Debug.WriteLine("COMMAND: " + list_id);
MyGSViewModel gsvm = new MyGSViewModel();
gsvm.removeItem(realm_id, list_id);
});
}
}
}
}
当调用removeItem方法时,视图没有刷新,并且该项目不会从ListView中删除,可能问题是关于CollectionChanged但我不知道如何修复它。
注意:在Android设备中进行调试
答案 0 :(得分:1)
有几件事。通常使用System.ComponentModel.INotifyPropertyChanged
代替INotifyCollectionChanged
。如果切换到那个并实现更常见的绑定模式,ViewModel将如下所示:
public class MyGSViewModel: INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection < SchItem > Items {
get { return _items; }
private set {
if(_items != value) {
_items = value;
OnPropertyChanged(); //Execute the event anytime an object is removed or added
}
}
}
public MyGSViewModel() {
Items = new ObservableCollection<SchItem>();
//Item Population
}
public void removeItem(int rid, int lid) {
SchItem myItem = Items[lid];
Items.Remove(myItem); //If an object is removed, the OnPropertyChanged() method will be run from 'Items's setter
}
protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
我还建议将OnPropertyChanged
方法和PropertyChanged
事件移动到基本ViewModel中,以便所有ViewModel都可以从基础继承,并且在任何地方都没有重复该代码。
*修改:注意到您在TapCommand
课程中定义了SchItem
。在那里,每次运行该命令时,您都在新建一个MyGSViewModel
实例。因此,除非MyGSViewModel
中的所有内容都设置为静态(我不建议这样做),否则这不会影响您的MyGS
页面。除了我上面建议的内容之外,我建议您使用Tapped
事件而不是Command
,因为您需要将多个参数传递到removeItem
方法中。
要做到这一点......
在您的XAML中:
<Button Tapped="OnItemTapped"/>
-OR -
<Label>
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="OnItemTapped"/>
</Label.GestureRecognizers>
</Label>
在MyGS
ContentPage
:
public partial class MyGS : ContentPage {
private MyGSViewModel _viewModel;
public MyGS() {
InitializeComponent();
BindingContext = _viewModel = new MyGSViewModel();
}
private void OnItemTapped(object sender, EventArgs e) {
SchItem item = (SchItem)((Image)sender).BindingContext;
if(item == null) { return; }
_viewModel.removeItem(item.realm_id, item.list_id);
}
}