H
H
Hlebushek99992021-02-15 13:23:26
WPF
Hlebushek9999, 2021-02-15 13:23:26

Problems with selection in ListBox after deleting an item, how to fix it?

There is such a problem, after deleting an element, I programmatically select the next one if there is one, but as soon as I press the arrow to switch the selection further, it is reset and the very first element is selected. I need to be able to move the arrows back and forth from the selected element.
For example: I remove the fifth element, then select the next one i.e. it turns out the fifth, everything is selected, I press the down arrow and instead of the sixth one, 1 is selected, this is the problem.
Element XAML:

<ListBox x:Name="listBox_CollectionItems" Grid.Column="2" Margin="5,0,0,0" SelectionMode="Extended"  HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="ListBox_CollectionItems_SelectionChanged" IsSynchronizedWithCurrentItem="True">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid MaxHeight="98">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="167" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Grid.RowSpan="2" HorizontalAlignment="Center" Height="94" Margin="0,2,0,2" VerticalAlignment="Top" Stretch="Uniform" Source="{Binding Path=Preview}"/>
                            <StackPanel Margin="5,2,0,2" Grid.Column="1">
                                <TextBlock TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding Path=Path}"/>
                                <TextBlock TextWrapping="Wrap" VerticalAlignment="Top" Foreground="Gray" Text="{Binding Path=Description}"/>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Items are added to the listBox_CollectionItems.Items collection through a loop.
I remove the element like this:
int currentCollectionItemIndex = listBox_CollectionItems.SelectedIndex;
listBox_CollectionItems.Items.RemoveAt(currentCollectionItemIndex);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-stream, 2021-02-15
@d-stream

does anything fit into listBox_CollectionItems.SelectedIndex after deletion?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question