<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); }
}
}
本文来自ny_dsc的博客,原文地址:http://hi.baidu.com/ny_dsc/blog/item/2bc69a31fdfb3186a8018e9a.html