не удается очистить коллекцию WPF ListBox.SelectedItems

Я не могу очистить коллекцию SelectedItems привязанного к данным WPF ListBox. Я попытался вызвать ListBox.SelectedItems.Clear (), я попытался установить SelectedIndex в -1, установить SelectedItem в ноль и вызвать ListBox.UnselectAll (). Во время отладки кажется, что либо назначения не выполняются, либо что-то сбрасывает коллекцию SelectedItems, но я не уверен, что именно. Я поставил точку останова в обратном вызове SelectionChanged, и он никогда не попадал неожиданно, но член SelectedItems.Count всегда равен по крайней мере 1 (иногда больше 1, так как режим выбора этого ListBox - MultiExtended).

Кто-нибудь видел это раньше и знает, что я делаю не так? Этот вопрос выглядит точно так же, как этот:WPF - Как очистить выделение из ListView?

за исключением этого поста, Sonny Boy использует ListView, а я использую ListBox. В любом случае, голосование после ответа должно было вызвать ListView.UnselectAll (), который не работает в моем случае.

Я чувствую, что, должно быть, делаю что-то совершенно очевидно неправильное, поскольку очистка выбора должна быть довольно простой.

ПРИМЕЧАНИЕ. Просто чтобы прояснить ситуацию, я не хочу удалять выборки из ListBox, я просто хочу, чтобы ничего не выбиралось.

Спасибо!

                            <ListBox Background="{StaticResource ResourceKey=DarkGray}" Name="lbx_subimageThumbnails" Margin="6,6,6,0" ItemsSource="{Binding ElementName=lbx_thumbnails, Path=SelectedItem.Swatches}" Style="{StaticResource WPTemplate}" SelectionMode="Extended" Height="{Binding ElementName=sld_swatchRows, Path=Value}" VerticalAlignment="Top" SelectionChanged="lbx_subimageThumbnails_SelectionChanged" DataContext="{Binding}">
                            <ListBox.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <WrapPanel HorizontalAlignment="Stretch" />
                                </ItemsPanelTemplate>
                            </ListBox.ItemsPanel>
                            <ListBox.ItemContainerStyle>
                                <Style TargetType="{x:Type ListBoxItem}">
                                    <Setter Property="Visibility" Value="{Binding Path=Vis}" />
                                </Style>
                            </ListBox.ItemContainerStyle>
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Width="270" Height="270" Margin="5,5,5,5" Tag="{Binding}" Name="lbx_swatchThumbnail" Background="{StaticResource ResourceKey=LightGray}" PreviewMouseLeftButtonDown="lbx_swatchThumbnail_PreviewMouseLeftButtonDown" PreviewMouseMove="lbx_swatchThumbnail_PreviewMouseMove">
                                        <Grid.LayoutTransform>
                                            <ScaleTransform CenterX="0" CenterY="0" ScaleX="0.50" ScaleY="0.50" />
                                        </Grid.LayoutTransform>
                                        <Grid.ContextMenu>
                                            <ContextMenu>
                                                <MenuItem Header="Sync selected" Click="btn_syncSwatch_Click" />
                                                <MenuItem Header="Re-export selected" Click="btn_exportSelected_Click"/>
                        ,                        <MenuItem Header="Set as default thumbnail" Click="btn_setThumbnail_Click"/>
                                                <MenuItem Header="Delete selected" Click="btn_deleteSwatch_Click"/>
                                                <MenuItem Header="Show in Explorer" Click="mnu_showSwatchesInExplorer_Click" />
                                                <MenuItem Header="Create Frames" Click="mnu_createFrames_Click" ToolTip="Creates FRAMEs groups to your PSD file under the Group associated with the selected swatch. DO NOT RE-ORDER OR RENAME THE GENERATED groups!" />
                                                <MenuItem Header="Create MIPs" Click="mnu_createMIPs_Click" ToolTip="Creates MIPs groups to your PSD file under the Group associated with the selected swatch. DO NOT RE-ORDER OR RENAME THE GENERATED groups!" />
                                            </ContextMenu>
                                        </Grid.ContextMenu>
                                        <Border BorderBrush="Black" BorderThickness="1">
                                            <Grid ToolTip="{Binding Path=Texture}">
                                                <Image VerticalAlignment="Center" HorizontalAlignment="Center" PhotoLoader:Loader.DisplayOption="Preview" PhotoLoader:Loader.DisplayWaitingAnimationDuringLoading="True" PhotoLoader:Loader.Source="{Binding Path=Texture}" PhotoLoader:Loader.DisplayErrorThumbnailOnError="True" Width="256" Height="256" />
                                                <TextBlock VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0,10,0,0" FontSize="20"  Text="{Binding Path=Group}" Background="Black" Foreground="White"/>
                                                <TextBlock VerticalAlignment="Bottom"  HorizontalAlignment="Center" Background="Black" Margin="0,0,0,10" FontSize="20" Foreground="White">
                                                    <TextBlock.Text>
                                                        <MultiBinding StringFormat="{}{0} x {1} {2}" >
                                                            <Binding Path="Width" />
                                                            <Binding Path="Height" />
                                                            <Binding Path="Format" />
                                                        </MultiBinding>
                                                    </TextBlock.Text>
                                                </TextBlock>
                                            </Grid>
                                        </Border>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>


        // this callback kicks everything off. 
        private void btn_editSwatch_Click(object sender, RoutedEventArgs e)
        {
            // get a list of the selected indices - we will have to unselect the texture source and reselect it after the re-export in order to force the thumbnail display to update
            // so we will save a list of indices to reselect them after the export
            List selectedIndices = new List();
            for (int i = 0; i < lbx_subimageThumbnails.Items.Count; i++)
            {
                if (lbx_subimageThumbnails.SelectedItems.Contains(lbx_subimageThumbnails.Items[i]))
                {
                    selectedIndices.Add(i);
                }
            }<p></p>

<pre><code>        // store the index of the selected texture source to reselect it after the re-export
        int selIndex = lbx_thumbnails.SelectedIndex;

        // edit and re-export the selected thumbnails
        if (this.EditThumbnails(lbx_subimageThumbnails.SelectedItems, lbx_thumbnails.SelectedItem))
        {

            // re-select the texture source
            lbx_thumbnails.SelectedIndex = selIndex;

            // re-select the previously selected thumbnails.
            foreach (int index in selectedIndices)
            {
                if (!lbx_subimageThumbnails.SelectedItems.Contains(lbx_subimageThumbnails.Items[index]))
                {
                    lbx_subimageThumbnails.SelectedItems.Add(lbx_subimageThumbnails.Items[index]);
                }
            }
        }
    }

    private void lbx_subimageThumbnails_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox textureSelector = sender as ListBox;
        if (textureSelector != null)
        {
            //update some UI elements
        }
    }

    /*
    this is the SelectionChanged callback for another listbox which is bound as the ItemSource of lbx_subimageThumbnails. When the selection here changes, we default the selection of the subimage listbox to the first subimage after first clearing the selected items in the subimage listbox
    */
    private void lbx_thumbnails_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // clear the previous swatch selection and select the first thumbnail
        // None of these methods works. after each, lbx_subimageThumbnails.SelectedItems.Count is still >= 1
        // Also, trying to set the SelectedIndex doesn't take. After the assignment, debugger shows                          
        // SelectedIndex is still 0 
        lbx_subimageThumbnails.SelectedIndex = -1;
        lbx_subimageThumbnails.SelectedIndex = -1;

        // Trying to set SelectedItem to null doesn't work...after assignment, SelectedItem is still a vaild
        // reference
        this.lbx_subimageThumbnails.SelectedItem = null;
        if (lbx_subimageThumbnails.SelectedItems.Count > 0)
        {
            lbx_subimageThumbnails.UnselectAll();
            lbx_subimageThumbnails.SelectedItems.Clear();
        }

        lbx_subimageThumbnails.SelectedIndex = 0;

        // reset the preview pane size
        sld_previewSize.Value = 1.0;
    }
</code></pre>

Ответы на вопрос(1)

Ваш ответ на вопрос