本文介绍了删除MVVM中列表中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大家好我能用这种方法添加项目 public ObservableCollection< CartData> cartData { get { if (App.Current._cartData == null ) { App.Current._cartData = new ObservableCollection< CartData>(); } return App.Current._cartData; } set { SetProperty( ref App.Current._cartData, value ); } } public CartData(){ cartData.Add( new CartData {Cakename = this .CakeName,Cakeprice = App.Current.cakeprice,ImagePath = bitmapimage,Caketype = App.Current.caketype,Cakesize = App.Current.cakesize}); } 它绑定到列表视图,现在我试图删除该项目如果选择某个项目并按下按钮。我如何知道列表中所选项目的索引?解决方案 向viewmodel添加第二个属性: public CartData SelectedCartData 并在XAML中绑定listview的Selected属性,确保将Mode设置为TwoWay。这样,绑定就是从cartData集合中提取数据并将所选值推回到viewmodel中。一旦发生这种情况,您可以致电: cartData.Remove(SelectedCartData); 尝试 绑定到ListBox(或其他项控件)的选定项目 [ ^ ] ListView MultiSelect,MVVM和RoutedCommands [ ^ ] MVVM多选列表框 [ ^ hello guys i was able to add items using this methodpublic ObservableCollection<CartData> cartData { get { if (App.Current._cartData == null) { App.Current._cartData = new ObservableCollection<CartData>(); } return App.Current._cartData; } set { SetProperty(ref App.Current._cartData, value); } }public CartData(){cartData.Add(new CartData { Cakename = this.CakeName, Cakeprice = App.Current.cakeprice,ImagePath=bitmapimage,Caketype=App.Current.caketype,Cakesize=App.Current.cakesize });}it is binded to the listview, now im trying to remove the item if certain item is selected and pressed a button. How do i know the Index of the selected item in the list? 解决方案 Add a second property to the viewmodel:public CartData SelectedCartDataand bind the Selected property of the listview in XAML making sure to set the Mode to TwoWay. This way the binding is pulling data from the cartData collection and pushing the selected value back into the viewmodel. Once this happens, you can then call:cartData.Remove(SelectedCartData);TryBinding to the selected items of a ListBox (or another items controls)[^]ListView MultiSelect, MVVM and RoutedCommands[^]MVVM Multiselect Listbox[^] 这篇关于删除MVVM中列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-25 04:16