suu
suu

Reputation: 165

shift +click functionality on listbox item using WPF

I need to add functionality on List box Item where the user can select the item by clicking each item individually and can also do shift+click to select a series of items in the list.

<ListBox ItemsSource="{Binding ItemFields, Mode=TwoWay}"
         VerticalAlignment="Stretch" HorizontalAlignment="Left"
         Margin="16,156,0,34" Name="fRListbox" Width="499" >                   
    <ListBox.ItemContainerStyle>                            
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="reportDatagrid_MouseDown"/>                              
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

and on xaml.cs I wrote below code:

private void ListItem_MouseClick(object sender, MouseButtonEventArgs e)
{
    if ((e.LeftButton == MouseButtonState.Pressed) && Keyboard.IsKeyDown(Key.RightShift))
    {
        fRListbox.SelectionMode = SelectionMode.Extended;
    }
    else if ((e.LeftButton == MouseButtonState.Pressed) && Keyboard.IsKeyDown(Key.LeftShift))
    {
        fRListbox.SelectionMode = SelectionMode.Multiple;
    }
    else if (e.LeftButton == MouseButtonState.Pressed)
    {
        fRListbox.SelectionMode = SelectionMode.Multiple;
    }
}

But Shift +Click functionality is not working. I am new to WPF can anyone guide me.

Upvotes: 5

Views: 6064

Answers (1)

Barracoder
Barracoder

Reputation: 3764

If you're happy for users to select items by holding the Ctrl key down when clicking individual items (like Windows Explorer and pretty much every other type of list) then setting SelectionMode to Extended is the simplest way to achieve single and multiple selections using the Ctrl and Shift keys.

<ListBox ItemsSource="{Binding ValuesView}" SelectionMode="Extended" />

Upvotes: 8

Related Questions