1
votes

I have a ListView with Extended SelectionMode. By default when I press a left button down it selects an item and when I move the mouse cursor (slowly) it moves the selection (as long as the button is still down).

Since I am implementing Drag and Drop on top of the list it becomes a little annoying. How can I prevent it from changing a selected item when a mouse button is down? I've tried to say e.Handled=true in the PreviewMouseMove but it didn't help.

1

1 Answers

5
votes

Update
The last solution was not working. This is a combo of two events that disables the mousemove selection. The problem is that when selecting an already selected item (no SelectionChanged occurs) then we can still move the mouse up or down to change the selection. The only way I found to get around this was to trick the ListView into selecting the same item again. This might be inconvenient if you have functionality for selection changed but otherwise this seems to get the job done.

<ListView SelectionMode="Extended"
            Name="listView">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <EventSetter Event="Selected" Handler="listViewItem_Selected"/>
            <EventSetter Event="PreviewMouseDown" Handler="listViewItem_PreviewMouseDown"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

And in the EventHandlers

void listViewItem_Selected(object sender, RoutedEventArgs e)
{
    listView.ReleaseMouseCapture();
}
private void listViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ListViewItem listViewItem = sender as ListViewItem;
    if (listViewItem.IsSelected == true)
    {
        // Unselecting the item in the Preview event
        // "tricks" the ListView into selecting it again
        listViewItem.IsSelected = false;
    }
}