views:

60

answers:

1

I have a really strage behaviour. I have a ListBox in the View with a DataTemplate for its items including ViewModels. I bind the IsSelected to my ViewModel and use SelectionMode="Extended". Everything works fine. BUT if I add VirtualiuationMode="Recycling" the I get the wrong items. To reproduce: select items with Ctrl, then scroll down and select just one item. The normal behaviour deselects all items and just select the last one without holded Ctrl. But if I check my ViewModel all the old items are selected!?!

<Grid>
    <StackPanel>
        <ListBox ItemsSource="{Binding People}" MaxHeight="100"
                 SelectionMode="Extended"
                 VirtualizationMode="Recycling">
            <!--VirtualizingStackPanel.IsVirtualizing="True">-->

            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />

                </Style>

            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>

                    <views:PeopleView />

                </DataTemplate>

            </ListBox.ItemTemplate>
        </ListBox>
        <Button Click="Button_Click">
            OK
        </Button>
    </StackPanel>
</Grid>

The item template

<UserControl x:Class="WpfApplication1.View.PeopleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="Auto" Width="Auto">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" SharedSizeGroup="A"/>
        <ColumnDefinition Width="Auto" SharedSizeGroup="B"/>
    </Grid.ColumnDefinitions>
    <TextBox Text="{Binding Path=Name}" 
             Name="tbx_Name" 
           Grid.Column="0"/>

    <CheckBox IsChecked="{Binding Path=IstAktiv}"
        Name="cbx_IstAktiv" 
              Grid.Column="1"/>

</Grid>

Any idea?

A: 

I got a workaround but why do I have to change it "manually" in the change event and not by databinding?

    private void Lbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox lbx = (ListBox)sender;
        foreach (PersonViewModel item in lbx.Items)
        {
            item.IsSelected = lbx.SelectedItems.Contains(item);
        }
    }
KCT