无法清除 WPF ListBox.SelectedItems 集合 [英] can't clear WPF ListBox.SelectedItems collection

查看:15
本文介绍了无法清除 WPF ListBox.SelectedItems 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法清除数据绑定 WPF ListBox 的 SelectedItems 集合.我尝试调用 ListBox.SelectedItems.Clear(),尝试将 SelectedIndex 设置为 -1,将 SelectedItem 设置为 null 并调用 ListBox.UnselectAll().在调试时,似乎要么没有分配任务,要么正在重置 SelectedItems 集合,但我不确定是什么.我在 SelectionChanged 回调中设置了一个断点,它永远不会被意外击中,但 SelectedItems.Count 成员始终至少为 1(有时大于 1,因为此 ListBox 的选择模式是 MultiExtended).

I can't seem to get the SelectedItems collection of a data bound WPF ListBox to clear. I've tried calling ListBox.SelectedItems.Clear(), i've tried setting the SelectedIndex to -1, setting the SelectedItem to null and calling ListBox.UnselectAll(). While debugging it appears that either the assignments don't take or something is resetting the SelectedItems collection, but I'm not sure what. I put a breakpoint in the SelectionChanged callback and it never gets hit unexpectedly yet the SelectedItems.Count member is always at least 1 (sometimes more than 1 since this ListBox's selection mode is MultiExtended).

有没有人见过这个并且知道我做错了什么?这个问题似乎与这个问题完全相同:WPF - 如何从 ListView 中清除选择?

Has anyone seen this before and know what I'm doing wrong? This question is seemingly exactly the same as this one: WPF - How to clear selection from ListView?

除了在那篇文章中,Sonny Boy 使用的是 ListView,而我使用的是 ListBox.无论如何,投票的答案是调用 ListView.UnselectAll() 这在我的情况下不起作用.

except in that post, Sonny Boy is using a ListView and I'm using a ListBox. In any case, the voted upon answer was to call ListView.UnselectAll() which doesn't work in my case.

我觉得我必须做一些非常明显的错误,因为清除选择应该非常简单.

I feel like I must be doing something very obviously wrong as clearing the selection should be pretty straight forward.

注意:为了清楚起见,我不想从 ListBox 中删除选择,我只想不选择任何内容.

NOTE: Just to be clear, I don't want to remove the selections from the ListBox, I just want nothing to be selected.

谢谢!

                            <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);
                }
            }
        // 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;
    }

推荐答案

您是否在 ListBox 中的项目上覆盖了 Equals()GetHashCode()?我可以通过以下方式复制它:

Have you overidden Equals() and GetHashCode() on the items in the ListBox? I can replicate this by:

  1. 选择列表中的一项.
  2. 更改项目的属性会导致其哈希码发生变化.
  3. 选择不同的项目.

第一项未从 SelectedItems 中删除,也无法按照您描述的方式手动删除.即使 SelectionMode 是单一的也是这种情况,并且如果您重新选择第一项,将导致抛出异常.

The first item is not removed from SelectedItems and cannot be removed manually the in way you describe. This is the case even when SelectionMode is single, and will result in an exception being thrown should you re-select the first item.

这篇关于无法清除 WPF ListBox.SelectedItems 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆