Deselecting WPF with Advanced Selection

I have a simple list with advanced selection mode. Selection works almost perfectly, as it does in Explorer. But de-selection does not really work very well. I want that when I click on something outside the range of the items in the list, I want all the items to be undone. In my opinion, I didn’t do this by default, and I did a dirty hack that included selectionchanged and mouseup to hack it. But there must be a better way. Any ideas?

+5
source share
2 answers

It’s not so dirty to add undo functionality and you are on the right track. The main problem is that by default ListBoxItems inside the ListBox will stretch completely, making it pretty tough not to click on one.

Here's an example ListBox that modifies the default ItemContainerStyle, so the items just occupy the left side of the list, and there’s also some space between them.

<ListBox SelectionMode="Extended"
         Width="200" Mouse.MouseDown="ListBox_MouseDown">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background"
                    Value="LightBlue" />
            <Setter Property="Margin"
                    Value="2" />
            <Setter Property="Padding"
                    Value="2" />
            <Setter Property="Width"
                    Value="100" />
            <Setter Property="HorizontalAlignment"
                    Value="Left" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem >Item 1</ListBoxItem>
    <ListBoxItem >Item 2</ListBoxItem>
    <ListBoxItem >Item 3</ListBoxItem>
    <ListBoxItem >Item 4</ListBoxItem>
</ListBox>

, SelectedItem null EventHandler. ListBoxItem, MouseDown/Click .., SelectedItem SelectedItems. - RoutedEvents MouseDown ListBox , . - ListBox , .

private void ListBox_MouseDown(object sender, MouseButtonEventArgs e)
{
    (sender as ListBox).SelectedItem = null;
}
+3

myListBox. SelectedItems.Clear(). , .

+3

All Articles