简体   繁体   English

列表框:一旦达到最大限制,如何取消选择/取消选择所选项目?

[英]ListBox: How to deselect/unselect item selected once the maximum limit has been met?

I am using manual limit of ListBox selected items to 5. 我正在使用ListBox所选项目的手动限制为5。

I tried different approaches including some solution applied in some other related issue but still can't make it. 我尝试了不同的方法,包括在其他一些相关问题中应用的解决方案,但仍然无法实现。

I already tried: this but I cannot follow using "...attach onto the SelectionChanged event". 我已经尝试过: 这个 ,但我不能跟着使用“...附着到SelectionChanged事件”。 I mean how to do that? 我是说该怎么做?

this :but it clears all the selected items leaving no selected items. :但是它清除所有选中的项目,而没有选中的项目。

and even setting the .SelectedIndex to -1 or null and the same thing happened. 甚至将.SelectedIndex设置为-1或null都发生了同样的事情。 It deselected every selected items. 它取消选择每个选定的项目。

etc... 等等...

All I want to do is just to deselect(hope this make sense) the last selected item once the limitation is met. 我要做的就是在符合限制后取消选择(希望这样做)最后选择的项目。

Or worst solution : Can I disable my ListBox but still displaying the selected items(meaning still highlighted)? 或更糟糕的解决方案:我可以禁用我的列表框,但仍显示所选项目(意味着仍突出显示)吗?

I tried most if in the SelectionChanged and some on Mouse_Down Event 如果在SelectionChangedMouse_Down事件中尝试了大部分尝试,

If you follow the answer you linked to then you arrive at something like this: 如果您遵循链接到的答案,那么您将得到如下内容:

XAML XAML

<ListBox x:Name="myListBox" SelectionChanged="myListBox_SelectionChanged" SelectionMode="Multiple">
...
</ListBox>

Code behind 后面的代码

void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // remove items from the end until at most 5 items are in the list
    while (myListBox.SelectedItems.Count > 5)
    {
        myListBox.SelectedItems.RemoveAt(SelectedItems.Count - 1);
    }
}

In WPF you could disable all unselected items when the maximum is reached: 在WPF中,您可以在达到最大值时禁用所有未选择的项目:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource AncestorType=ListBox}}" Value="5"/>
                    <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="false"/>
                </MultiDataTrigger.Conditions>
                <Setter Property="IsEnabled" Value="False"/>
            </MultiDataTrigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

(You might want to override the input bindings though as Ctrl+A will still select everything) (您可能想覆盖输入绑定,尽管Ctrl+A仍会选择所有内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM