WPF ListBox 鼠标拖拽多选

<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); }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值