Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does WP8 LongListSelector incorrectly re-use Checked state of CheckBox?

I have a WP8 LongListSelector with the following template:

    <DataTemplate x:Key="ItemTemplate">
        <Grid Margin="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="110"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <controls:BlockImageControl 
                        Grid.Column="0"
                        Width="110"
                        Height="110"
                        Background="Transparent" />
            <TextBlock x:Name="Name" 
                            Grid.Column="1"
                            Text="{Binding ScreenName}" 
                            FontSize="{StaticResource PhoneFontSizeLarge}"
                            FontWeight="Bold"
                            VerticalAlignment="Center"/>
            <CheckBox x:Name="Unblock" Grid.Column="2" VerticalAlignment="Center"
                      Tap="BlocksList_Tap"
                      IsChecked="false"
                      />
        </Grid>
    </DataTemplate>

As you can see there is a checkbox at the end of each cell item, which enables the user to select multiple items. IsChecked is false by default.

The problem is that the LongListSelector seems to be caching the Checked state of my checkbox. If I check the very first, item, then scroll down partway, after about 30 or so items, I see another item checked which I did not select. The rest of the bindings work. It is as if it is ignoring the "IsChecked" property in the template. I tried binding the IsChecked attribute to a property, no luck.

Does anyone know if this is a bug, and if not, how I can correct this behavior?

Thanks!

enter image description here

like image 252
esilver Avatar asked Mar 01 '13 18:03

esilver


1 Answers

Not a bug, although it might look like a bug at first. What you see is the effect of ui virtualization, basically LongListSelector recycles data templates instead of creating new ones to improve performance. One known side effect of recycling is that if your data template contains controls that maintain their own state, CheckBox for example, that state will carry over to the new item.

To solve this issue you need to manage control state externally, i.e. in the view model. In your particular case IsChecked property of CheckBox must be bound to a property of view model. And make sure to use two way binding.

like image 110
Denis Avatar answered Sep 30 '22 17:09

Denis