如何正确绑定和更新Xamarin.FormsListView?使用MVVM模式,我有一个模型、ViewModel和View,其中包含一个ListView。ListView绑定到ViewModel的成员,它是Model类的ObservableCollection。我可以使初始显示绑定起作用,并在对视图进行操作时更新相应行的模型类的属性,但我无法刷新视图,无法从ObservableCollection中的模型类中提取数据。ListView类不包含无效或强制刷新的方法,这将解决我的问题。更新模型上的数据后如何刷新ListView?这是我正在尝试做的一个简单示例:每一行都包含一个按钮和一个标签。单击按钮后,我可以更新标签,这将反映在屏幕上。我需要做的是更新模型,从而强制更新视图。但是,我无法让它工作。在实际应用程序中,模型的更新将在业务逻辑层进行,而不是在视图中进行,之后我需要强制刷新ListView。示例代码:usingSystem;使用System.Collections.ObjectModel;使用Xamarin.Forms;命名空间ListViewTest{公共类模型{publicstaticintids=0;公共模型(字符串计数){Id=+1;计数=计数;}publicintId{得到;放;}公共字符串计数{得到;放;}}publicclassModelList:ObservableCollection{}publicclassViewModel{ModelListlist=newModelList();publicModelListViewModelList{get{返回列表;}设置{列表=值;}}}publicpartialclassMainPage:ContentPage{publicViewModelviewModel;publicclassDataCell:ViewCell{publicDataCell(){varBtn=newButton();Btn.Text="点击";var数据=新标签();Data.SetBinding(Label.TextProperty,"Count");Btn.Clicked+=(objectsender,EventArgse)=>{Modelmodel=(Model)(((Button)sender).Parent.BindingContext);intcount=Convert.ToInt32(model.Count);计数++;model.Count=count.ToString();//这里需要从数据源刷新ListView...怎么办???};StackLayouts=newStackLayout();s.Orientation=StackOrientation.Horizo??ntal;s.Children.Add(Btn);s.Children.Add(数据);这个.View=s;}}publicMainPage(){viewModel=newViewModel();viewModel.ViewModelList.Add(新模型("0"));viewModel.ViewModelList.Add(新模型("0"));初始化组件();}publicvoidInitializeComponent(){ListViewlistView=newListView{ItemsSource=viewModel.ViewModelList,ItemTemplate=newDataTemplate(()=>{returnnewDataCell();})};内容=列表视图;}}}我认为你的模型需要实现INotifyPropertyChanged所以UI知道模型中的值发生了如下变化:protectedvirtualvoidOnPropertyChanged(stringpropertyName){PropertyChangedEventHandlerhandler=PropertyChanged;如果(处理程序!=)处理程序(这个,新的PropertyChangedEventArgs(propertyName));}protectedboolSetField(refTfield,Tvalue,stringpropertyName){if(EqualityComparer.Default.Equals(field,value))returnfalse;字段=值;OnPropertyChanged(属性名);返回真;}//props私有字符串_count;publicstringCount{get{return_count;}set{SetField(ref_count,value,"Count");}}}从ViewModelList属性中删除“set”方法。每当您使用ObservableCollection时,只需更改该集合中的项目。切勿将其替换为另一个ObservableCollection。以上就是C#学习教程:HowdoyoucorrectlybindandupdatetheXamarin.FormsListView?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
