WPF使ListBox支持手势多选功能

手势功能在手持平台应用较为丰富,PC上的应用还不是很多,不过还是有一些软件已应用这个功能如遨游浏览器等,应用得当还是相当可以丰富用户的互交体验的。

接下来我将介绍如何为ListBox添加手势功能支持。

这里我们用到了InkCanvas,它有一个Gesture事件,在这个事件中我们可以得到我们所画出的形状的区域及

e.Strokes[0].GetGeometry(),然后我们对这ListBox的这个区域做命中检查VisualTreeHelper.HitTest,从中过滤出我们想选中的多个ListBoxItem.

效果图:

t3_thumb[3]t4_thumb[2]

代码如下:

查看XAML
 //鼠标指针模式
        private void NoneMode_Click(object sender, RoutedEventArgs e)
        {
            m_ic.EditingMode = InkCanvasEditingMode.None;
        }
        //手势选择模式
        private void SelectionMode_Click(object sender, RoutedEventArgs e)
        {
            m_ic.EditingMode = InkCanvasEditingMode.GestureOnly;
            listBox1.SelectedItem = null;
        }
        //得到选中的项
        private void GetSelected_Click(object sender, RoutedEventArgs e)
        {
           int count = listBox1.SelectedItems.Count;
           StringBuilder msg = new StringBuilder("Selected items:");
            for (int i = 0; i < count; i++)
            {
                var item = listBox1.SelectedItems[i] as ListBoxItem;
                msg.Append(item.Content);
                msg.Append(",");
            }
            msg.Append("Count:");
            msg.Append((count-1).ToString());
            MessageBox.Show(msg.ToString());
        }

        //被选中的项
        private List<ListBoxItem> _selections = new List<ListBoxItem>(5);   
        //InkCanvas的手势事件
        private void m_ic_Gesture(object sender, InkCanvasGestureEventArgs e)
        {
            listBox1.SelectedItem = null;    //清空选择
            _selections.Clear();             //
            //命中检测手势区域中ListBox1内的控件
            VisualTreeHelper.HitTest(listBox1, OnFilter, OnResult, new GeometryHitTestParameters(e.Strokes[0].GetGeometry()));
            foreach (ListBoxItem item in _selections)
            {
                item.IsSelected = !item.IsSelected;
            }
        }

        //过滤检测
        private HitTestFilterBehavior OnFilter(DependencyObject potentialHitTestTarget)
        {
            ListBoxItem item = potentialHitTestTarget as ListBoxItem;
            if (item != null)   //查找是ListBoxItem的控件
            {
                _selections.Add(item);
                return HitTestFilterBehavior.ContinueSkipSelfAndChildren;
            }
            return HitTestFilterBehavior.ContinueSkipSelf;
        }

        private HitTestResultBehavior OnResult(HitTestResult result)
        {
            return HitTestResultBehavior.Continue;
        }

作者: YOYOFx

出处:https://www.cnblogs.com/maxzhang1985/p/12673160.html

版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。

欢迎大家关注微信号。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码) 微信公众平台
原文地址:https://www.cnblogs.com/maxzhang1985/p/1866211.html