0
votes

I am using manual limit of ListBox selected items to 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". 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. 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

2

2 Answers

2
votes

If you follow the answer you linked to then you arrive at something like this:

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);
    }
}
1
votes

In WPF you could disable all unselected items when the maximum is reached:

<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)