手势功能在手持平台应用较为丰富,PC上的应用还不是很多,不过还是有一些软件已应用这个功能如遨游浏览器等,应用得当还是相当可以丰富用户的互交体验的。
接下来我将介绍如何为ListBox添加手势功能支持。
这里我们用到了InkCanvas,它有一个Gesture事件,在这个事件中我们可以得到我们所画出的形状的区域及
e.Strokes[0].GetGeometry(),然后我们对这ListBox的这个区域做命中检查VisualTreeHelper.HitTest,从中过滤出我们想选中的多个ListBoxItem.
效果图:
代码如下:
查看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; }