【问题标题】:xamarin.forms : ListView not updating as expexctedxamarin.forms:ListView 未按预期更新
【发布时间】:2016-11-09 17:02:29
【问题描述】:

我已经使用我在 Windows 中显示的 Xamarin.Forms 构建了一个应用程序。 要求: - 点击列表视图中的项目 > - UI 中项目的显示值发生变化

这里是相关的 xaml 注意:我已经从后面的代码中设置了 ListView.ItemsSource

  <ListView.ItemTemplate > 
  <StackLayout  VerticalOptions="Center" HorizontalOptions="Center"  >
  <Label Text="Passo dopo passo" VerticalOptions="Center" HorizontalOptions="Center" />
  <Button Clicked="GetGroceries" Text="Get Groceries" ></Button>
  <ListView x:Name="lvGroceries" ItemTapped="GroceryItemTapped" >
  <ListView.ItemTemplate > 

这是后面的c#代码,当项目被点击时运行良好,但UI没有改变。


    public ObservableCollection oc;
    public void GroceryItemTapped (object o, ItemTappedEventArgs e )
    {
     if (e.Item == null ) {
         return;
     }
     var g = ((GroceryItem)e.Item);
     // oc is populated and exactly what I expect here
     foreach (var gr in oc)
     {
         // the next line grabs the item I want
         if (gr.GroceryId == g.GroceryId)
         {
             gr.GroceryName = "snot";
         }  } }

    // when the above code runs, the data is already in oc and this code ran
    lvGroceries.ItemsSource = oc;

想法?

【问题讨论】:

  • GroceryItem 是否实现了 INotifyPropertyChanged?

标签: c# xamarin xamarin.forms


【解决方案1】:

您需要将ListView 绑定到您的收藏:

<ListView x:Name="lvGroceries" ItemsSource="{Binding oc}" ItemTapped="GroceryItemTapped" >

您还需要设置您的ContentPage.BindingContext。您还需要实现INotifyPropertyChanged 并在您的收藏更新时运行OnPropertyChanged()。最后,您需要通过 oc.Add() 添加到您的集合中,而不是每次都重置 ItemSource,因为这会覆盖您的绑定。

强烈建议查看Xamarin Forms Binding Documentation

【讨论】:

  • 感谢您的指导。我会尝试的。当然,我一直在研究 Xamarin Docs。除非我尝试过,否则在这里问问题是不负责任的。
  • 好的。我只需要做你提到的四件事中的一件,但你会得到绿色的复选标记。我有一个类 GroceryItem,我必须在该类中实现 INotifyPropertyChanged 并为我正在更改的属性触发 OnPropertyChanged 事件。这个 msdn 文档真的帮助了我。 msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx
  • @pdschuller 很高兴它有所帮助,并感谢您为其他人添加链接!如果您遇到任何其他问题,请告诉我。
  • 感谢您提供有关相关问题的帮助。我这里有另一个帖子stackoverflow.com/questions/40558962/…
猜你喜欢
  • 2021-11-22
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2018-03-03
相关资源
最近更新 更多