【问题标题】:ListView binding only updating UI when scrollingListView 绑定仅在滚动时更新 UI
【发布时间】:2018-10-04 11:38:57
【问题描述】:

我有一个 Xamarin Forms 项目,使用 ViewModels 和 XAML 绑定。我有一个特定的 ListView,它绑定到特定对象的 ObservableCollection。

单击时我正在尝试更改按钮的颜色,我可以看到事件正在触发,并且 PropertyChanged 正在按预期工作,但是在我向下滚动 ListView 之前按钮不会更改颜色,以便它不再在视图中,然后向上滚动到它。一旦我往回滚动,我认为这会触发某种“让我知道你的状态,以便我可以显示你”的事件,然后该事件会发生变化。

下面是我的 XAML:

<ListView CachingStrategy="RecycleElement" ItemsSource="{Binding ListViewItems}" Margin="0,20,0,0" RowHeight="130" SeparatorVisibility="None" VerticalOptions="FillAndExpand" Grid.Column="1" Grid.Row ="0" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Button Command="{Binding HeatClickedCommand}" Margin="5,10,5,10" HorizontalOptions ="FillAndExpand" BackgroundColor="{Binding color_hex}" Grid.Column="1" TextColor="{StaticResource LightTextColor}" FontSize="Medium" Text="{Binding heat_title}"></Button>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

你可能注意到我使用的是CachingStrategy="RecycleElement" 这可能与此问题有关,其背后的原因在之前的 SO 帖子 here 中进行了解释。

基本上使用默认的 CachingStrategy 会导致意外结果。

【问题讨论】:

  • 您是否在您的集合中的模型上实现了 INotifyPropertyChanged 接口?
  • 嗯.. 这很尴尬,杰拉德,你又来救援了。如此简单的修复,我真的应该注意到但假设它会抱怨在没有接口的情况下实现 PropertyChangedEventHandler。再一次,请回答,我会给你你应得的代表
  • 没问题!将其更新为答案!

标签: xaml listview xamarin.forms observablecollection inotifypropertychanged


【解决方案1】:

要立即更新视图,您必须在模型上实现INotifyPropertyChanged 接口。有了这个接口,每当属性值发生变化时,都会通知 UI 并进行相应的更新。

每次滚动都会更新它的原因是单元格被重新绘制甚至完全重新填充。

不要错误地认为使用 ObservableCollection 会做到这一点,因为这只会反映集合结构中的更新,而不是其中的模型。

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 2021-08-21
    • 2019-11-19
    • 2018-06-01
    相关资源
    最近更新 更多