WPF MultiSelect模式下ListBox 实现多个ListBoxItem拖拽
WPF 的ListBox不支持很多常見的用戶習慣,如在Explorer中用鼠標可以選擇多項Item,并且點擊已經選擇的Item,按住鼠標左鍵可以將所有已選擇Item拖拽到指定的位置。本文簡單的實現了這一功能。
效果圖:
拖拽1個Item
?
拖拽多個Item
?
說明:
代碼下載地址:http://download.csdn.net/download/u012566751/6452323
代碼中使用了兩個類:
1.DragDropAdorner,用于拖拽過程中顯示預覽圖,代碼來自CSDN
2.ListBoxSelectionHelper,用于通過鼠標拖拽框選ListBoxItem,代碼來自Codeproject,作者略作修改
?
具體操作
1.創建一個WPF工程,WpfDragMultiSelect,主界面代碼如下:
<Grid><Grid.RowDefinitions><RowDefinition Height="5"/><RowDefinition Height="*"/><RowDefinition Height="5"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="5"/><ColumnDefinition Width="50"/><ColumnDefinition Width="5"/><ColumnDefinition Width="*"/><ColumnDefinition Width="5"/></Grid.ColumnDefinitions><Grid Grid.Row="1" Grid.Column="1" Background="Black"/><GridSplitter Grid.Row="1" Grid.Column="2"ShowsPreview="True"HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/><Grid Grid.Row="1" Grid.Column="3" Background="Gray"></Grid></Grid>
2.創建一個列表,使用數據綁定方式,數據類如下:
?數據類只有一個公共屬性Number,類型為int
?
主類添加代碼:
List<ListData> _list = new List<ListData>(); AdornerLayer mAdornerLayer = null; bool bIsDraging = false;public MainWindow(){InitializeComponent();for (int n = 0; n < 600; n++ ){this._list.Add(new ListData(n));}this.DataContext = _list;this.list.AllowDrop = true;this.list.QueryContinueDrag += delegate(object sender, QueryContinueDragEventArgs e){//_adornerLayer.Update();//this.list.Cursor = Cursors.Arrow; mAdornerLayer.Update();};}_list作為列表數據源
bIsDraging表示數據拖拽狀態
列表數據模板如下:
每個列表顯示為一個亮藍色(LightBlue)的正方形,在每個正方形中顯示該項綁定ListData對象的Number屬性。
最后一個Rectangle專門用于響應鼠標事件
在主界面中添加列表:
代碼:loc:ListBoxSelectionHelper.MultiSelect="True"??loc:ListBoxSelectionHelper.PreviewDrag="True" ,使用ListBoxSelectionHelper類實現鼠標拖拽框選功能
?
3.添加一個Grid,用于在拖拽過程中顯示預覽
<!--拖拽預覽--><Grid Width="100"Height="100"><Grid x:Name="gridAdorner" Visibility="Hidden"><Rectangle Width="50"Height="50"Fill="LightGray"/><TextBlock x:Name="textAdorner" Text="0"VerticalAlignment="Center"HorizontalAlignment="Center" Foreground="Red" FontSize="20"></TextBlock></Grid></Grid>
4.實現數據模板dt_Rectangle中聲明的事件,用以支持拖拽功能
分別響應PreviewMouseDown,PreviewMouseMove,PreviewMouseUp三個事件
PreviewMouseDown:判斷Item是否選為已選擇的Item,如果是則進入拖拽狀態,標記bIsDraging,并且截斷事件e.Handled = true;如果不截斷,ListBox會響應點擊事件,默認選擇當前Item
Rectangle_PreviewMouseMove:如果當前為拖拽狀態且鼠標左鍵按下,則開始拖拽。將gridAdorner作為拖拽預覽
Rectangle_PreviewMouseUp:關閉拖拽狀態
?
至此,已經完全實現拖拽多個Item功能。
?
轉載于:https://www.cnblogs.com/max198727/p/3387805.html
總結
以上是生活随笔為你收集整理的WPF MultiSelect模式下ListBox 实现多个ListBoxItem拖拽的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: phpMyAdmin安装
- 下一篇: C# 正则表达式过滤危险HTML