Xamarin ListView bound to ObservableCollection changing at random

故事扮演 提交于 2019-12-07 23:16:58

问题


Please consider the following issue:

I have a Xamarin Forms project, using ViewModels and XAML binding. I have a particular ListView that is bound to an ObservableCollection of a particular object.

The objects contain all the required information to display the following list of buttons:

<ListView 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>

When the page first loads, the colour_hex is set to either green, grey or red depending on a particular app state and information about the object. When the list is first displayed, all of the buttons that fit on the screen appear to display correctly, however the buttons at the end appear not to (The last 4 are supposed to be greyed out, and in Debug i've echo'd the colour and it should be grey).

The strange thing however, is that if some of the buttons are green, scrolling up and down quickly appears to change which buttons are set to green at random.

For example, say buttons 1 and 2 and red, but 3 is green, if I scroll down to say 15, and then back up to the top quickly, it may have changed so that 2 is now green and 3 red.

This only appears to happen on androids (phone and tablet), but I haven't tested it across a wide enough variety of devices yet to be able to conclusively say that. I just know it doesn't happen on Windows.

Checking Debug it looks that none of the colour changing functions or propertychanged functions are firing when this is happening, it looks to be like some kind of memory problem.

Any advise on this would be greatly appreciated.


回答1:


Have a look at the ListView.CachingStrategy property and what it does. That is probably what is causing this.

This setting determines how cells are being reused. If set to a wrong value (for your use-case) it might cause some strange behaviour.

More information can be found in the documentation: https://developer.xamarin.com/api/type/Xamarin.Forms.ListViewCachingStrategy/



来源:https://stackoverflow.com/questions/49983049/xamarin-listview-bound-to-observablecollection-changing-at-random

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!