<ListBox Name="listBox" SelectionMode="Extended">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="ListBoxItem.PreviewMouseLeftButtonDown" Handler="lbItem_PreviewMouseLeftButtonDown"/>
<EventSetter Event="ListBoxItem.PreviewMouseUp" Handler="lbItem_PreviewMouseUp"/>
<EventSetter Event="ListBoxItem.PreviewMouseMove" Handler="lbItem_PreviewMouseMove"/>
</Style>
</ListBox.Resources>
<x:Type TypeName="DependencyObject"/>
<x:Type TypeName="Visual"/>
<x:Type TypeName="UIElement"/>
<x:Type TypeName="FrameworkElement"/>
<x:Type TypeName="Control"/>
</ListBox>
private bool inMouseSelectionMode = false;
private List<ListBoxItem> selectedItems = new List<ListBoxItem>();
private void lbItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// MouseDown时清空已选Item
// 同时开始"inMouseSelectionMode"
foreach (var item in selectedItems)
{
item.ClearValue(ListBoxItem.BackgroundProperty);
item.ClearValue(TextElement.ForegroundProperty);
}
selectedItems.Clear();
inMouseSelectionMode = true;
}
private void lbItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
// MouseUp时停止"inMouseSelectionMode"
ListBoxItem mouseUpItem = sender as ListBoxItem;
inMouseSelectionMode = false;
}
private void lbItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
ListBoxItem mouseOverItem = sender as ListBoxItem;
if (mouseOverItem != null && inMouseSelectionMode && e.LeftButton == MouseButtonState.Pressed)
{
// Mouse所在的Item设置高亮
mouseOverItem.Background = SystemColors.HighlightBrush;
mouseOverItem.SetValue(TextElement.ForegroundProperty, SystemColors.HighlightTextBrush);
if (!selectedItems.Contains(mouseOverItem)) { selectedItems.Add(mouseOverItem); }
}
}