淺析WPF中控件拖拽與拖動(dòng)的實(shí)現(xiàn)
使用過(guò)office的visio軟件畫(huà)圖的小伙伴都知道,畫(huà)圖軟件分為兩部分,左側(cè)圖形庫(kù),存放各種圖標(biāo),右側(cè)是一個(gè)畫(huà)布,將左側(cè)圖形庫(kù)的圖標(biāo)控件拖拽到右側(cè)畫(huà)布,就會(huì)生成一個(gè)新的控件,并且可以自由拖動(dòng)。那如何在WPF程序中,實(shí)現(xiàn)類(lèi)似的功能呢?今天就以一個(gè)簡(jiǎn)單的小例子,簡(jiǎn)述如何在WPF中實(shí)現(xiàn)控件的拖拽和拖動(dòng),僅供學(xué)習(xí)分享使用,如有不足之處,還請(qǐng)指正。
涉及知識(shí)點(diǎn)
WPF控件的拖拽與拖動(dòng),主要涉及知識(shí)點(diǎn)如下所示:
- 容器布局,本示例采用左右布局,主容器采用Grid并分成兩列進(jìn)行布局,左側(cè)圖標(biāo)庫(kù)采用UniformGrid布局,右側(cè)畫(huà)布采用Canvas布局。
- 控件拖拽,當(dāng)圖標(biāo)庫(kù)中的圖標(biāo)控件被鼠標(biāo)按下時(shí),通過(guò)調(diào)用 DragDrop.DoDragDrop方法實(shí)現(xiàn)拖拽功能,并且設(shè)置畫(huà)布的AllowDrop屬性為true,并觸發(fā)拖拽松開(kāi)事件。
- 控件拖動(dòng),當(dāng)圖標(biāo)庫(kù)中的圖標(biāo)拖拽到新畫(huà)布容器后,就會(huì)生成一個(gè)新的控件,通過(guò)屬性按下事件,鼠標(biāo)移動(dòng)事件,鼠標(biāo)升起事件,來(lái)實(shí)現(xiàn)控件的拖動(dòng)。
實(shí)現(xiàn)步驟
1. 頁(yè)面布局
根據(jù)布局說(shuō)明,頁(yè)面分為左右兩部分【Grid容器】,左側(cè)圖標(biāo)庫(kù)【UniformGrid】,右側(cè)畫(huà)布【Canvas】,如下所示:
<Window x:Class="DemoDragAndDrop.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DemoDragAndDrop" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding WinLoadedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/> </i:EventTrigger> </i:Interaction.Triggers> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <Border Grid.Column="0" BorderBrush="LightGray" BorderThickness="1"></Border> <Border Grid.Column="1" BorderBrush="LightGray" BorderThickness="1"></Border> <UniformGrid Grid.Column="0" Columns="2" VerticalAlignment="Top"> <UniformGrid.Resources> <Style TargetType="TextBlock"> <Setter Property="Width" Value="100"></Setter> <Setter Property="Height" Value="40"></Setter> <Setter Property="FontSize" Value="18"></Setter> <Setter Property="TextAlignment" Value="Center"></Setter> <Setter Property="Padding" Value="10"></Setter> <Setter Property="Margin" Value="5"></Setter> <Setter Property="Background" Value="Blue"></Setter> <Setter Property="FontWeight" Value="Bold"></Setter> <Setter Property="Foreground" Value="White"></Setter> </Style> </UniformGrid.Resources> <TextBlock Text="文本" Tag="Text"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding IconMouseLeftDownCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBlock}}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> <TextBlock Text="按鈕" Tag="Button"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding IconMouseLeftDownCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBlock}}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> <TextBlock Text="單選按鈕"></TextBlock> <TextBlock Text="復(fù)選按鈕"></TextBlock> <TextBlock Text="圓形"></TextBlock> <TextBlock Text="長(zhǎng)方形"></TextBlock> <TextBlock Text="直線"></TextBlock> <TextBlock Text="三角形"></TextBlock> </UniformGrid> <Canvas x:Name="container" Grid.Column="1" AllowDrop="True" Background="White"> <i:Interaction.Triggers> <i:EventTrigger EventName="Drop"> <i:InvokeCommandAction Command="{Binding CanvasDropCommand}" PassEventArgsToCommand="True"/> </i:EventTrigger> </i:Interaction.Triggers> </Canvas> </Grid> </Window>
注意,在頁(yè)面布局中,為圖標(biāo)庫(kù)中的圖標(biāo)綁定了MouseLeftButtonDown事件命令,當(dāng)鼠標(biāo)左鍵按下時(shí)觸發(fā)對(duì)應(yīng)的事件,并開(kāi)始拖拽。如下所示:
private ICommand iconMouseLeftDownCommand; public ICommand IconMouseLeftDownCommand { get { if (iconMouseLeftDownCommand == null) { iconMouseLeftDownCommand = new RelayCommand<object>(IconMouseLeftDown); } return iconMouseLeftDownCommand; } } private void IconMouseLeftDown(object sender) { var tag = (sender as TextBlock)?.Tag?.ToString(); if (tag == null) { return; } var data = new DragDropData() { Tag = tag }; //開(kāi)啟準(zhǔn)備拖動(dòng)操作 DragDrop.DoDragDrop((DependencyObject)sender, data, DragDropEffects.Copy); }
注意,在調(diào)用DragDrop.DoDragDrop方法開(kāi)始拖拽時(shí),此方法有三個(gè)參數(shù)【DoDragDrop(DependencyObject dragSource, object data, DragDropEffects allowedEffects)】,說(shuō)明如下:
- 第一個(gè)參數(shù)是拖拽源控件。
- 第二個(gè)參數(shù)用于傳遞數(shù)據(jù),可以傳遞參數(shù),用于區(qū)分詳細(xì)信息。
- 第三個(gè)參數(shù)是拖拽效果
在畫(huà)布容器中松開(kāi)拖拽的鼠標(biāo)左鍵時(shí),觸發(fā)畫(huà)布Drop事件,在此事件中創(chuàng)建新的控件,如下所示:
private ICommand canvasDropCommand; public ICommand CanvasDropCommand { get { if (canvasDropCommand == null) { canvasDropCommand = new RelayCommand<DragEventArgs>(CanvasDrop); } return canvasDropCommand; } } private void CanvasDrop(DragEventArgs e) { var data = e.Data.GetData(typeof(DragDropData)) as DragDropData; if (data != null) { var position = e.GetPosition(this.containerCanvas); if (data.Tag == "Text") { //創(chuàng)建文本 Border border = new Border(); border.BorderThickness = new Thickness(1); border.BorderBrush = Brushes.Black; TextBlock text = new TextBlock() { Width = 120, Height = 30, Text = "文本1", FontSize = 14, Background = Brushes.LightGray, TextAlignment = TextAlignment.Center, Padding = new Thickness(5) }; border.Child = text; border.MouseDown += Container_Control_MouseDown; border.MouseMove += Container_Control_MouseMove; border.MouseUp += Container_Control_MouseUp; this.containerCanvas.Children.Add(border); Canvas.SetLeft(border, position.X - 60); Canvas.SetTop(border, position.Y - 15); } if (data.Tag == "Button") { Button button = new Button() { Width = 120, Height = 30, Content = "按鈕1", FontSize = 14, Background = Brushes.LightGray, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, Padding = new Thickness(5), BorderBrush = Brushes.Black, BorderThickness = new Thickness(1) }; button.AddHandler(Button.MouseDownEvent,new MouseButtonEventHandler( Container_Control_MouseDown),true); button.AddHandler(Button.MouseMoveEvent, new MouseEventHandler(Container_Control_MouseMove), true); button.AddHandler(Button.MouseUpEvent, new MouseButtonEventHandler(Container_Control_MouseUp), true); this.containerCanvas.Children.Add(button); Canvas.SetLeft(button, position.X - 60); Canvas.SetTop(button, position.Y - 15); } } }
注意:在此事件中,以下幾點(diǎn)需要注意:
- 通過(guò)e.Data.GetData方法獲取傳遞的參數(shù)。
- 通過(guò)e.GetPosition方法獲取鼠標(biāo)相對(duì)位置。參數(shù)是相對(duì)的對(duì)象,如Canvas容器等。
- 容器的Drop事件中,根據(jù)傳遞的內(nèi)容創(chuàng)建控件對(duì)象,并為新創(chuàng)建的控件對(duì)象綁定MouseDown,MouseMove,MouseUp方法。其中Button按鈕,由于鼠標(biāo)按下事件和本省自帶的Click事件相沖突,所以需要通過(guò)AddHandler方法添加鼠標(biāo)事件。
- 通過(guò)Canvas.SetLeft,Canvas.SetTop方法設(shè)置控件對(duì)象在畫(huà)布容器中的位置。
2. 控件拖動(dòng)
在控件對(duì)象的MouseDown,MouseMove,MouseUp三個(gè)事件中,實(shí)現(xiàn)控件的拖動(dòng)效果。即在MouseDown時(shí)開(kāi)始,MouseMove中不斷設(shè)置控件的Left,Top的值隨鼠標(biāo)而動(dòng),在MouseUp時(shí)停止。
private void Container_Control_MouseUp(object sender, MouseButtonEventArgs e) { if(e.LeftButton== MouseButtonState.Released) { Mouse.Capture(null); } } private void Container_Control_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { var position = e.GetPosition(this.containerCanvas); Canvas.SetLeft((UIElement)sender,position.X-60); Canvas.SetTop((UIElement)sender,position.Y-15); } } private void Container_Control_MouseDown(object sender, MouseButtonEventArgs e) { if(e.LeftButton ==MouseButtonState.Pressed) { Mouse.Capture((IInputElement)sender); } }
注意,啟動(dòng)Mouse.Capture功能是為了捕獲鼠標(biāo)的焦點(diǎn),使其在鼠標(biāo)移動(dòng)期間一直保持焦點(diǎn),防止鼠標(biāo)與控件分離。
示例效果
本示例主要為了說(shuō)明,只是簡(jiǎn)單地 實(shí)現(xiàn)了控件拖拽,拖動(dòng)等效果,具體如下所示:
到此這篇關(guān)于淺析WPF中控件拖拽與拖動(dòng)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)WPF控件拖拽與拖動(dòng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于動(dòng)態(tài)修改App.Config與web.Config的使用詳解
本篇文章是對(duì)動(dòng)態(tài)修改App.Config與web.Config的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C# OCR實(shí)現(xiàn)文字識(shí)別功能
OCR,中文叫做光學(xué)字符識(shí)別。它是利用光學(xué)技術(shù)和計(jì)算機(jī)技術(shù)把印在或?qū)懺诩埳系奈淖肿x取出來(lái),并轉(zhuǎn)換成一種計(jì)算機(jī)能夠接受、人又可以理解的格式。本文將利用OCR實(shí)現(xiàn)文字識(shí)別功能,感興趣的可以了解一下2022-11-11Unity UGUI的LayoutElement布局元素組件介紹使用示例
這篇文章主要為大家介紹了Unity UGUI的LayoutElement布局元素組件介紹使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Unity3D仿寫(xiě)B(tài)utton面板事件綁定功能
這篇文章主要為大家詳細(xì)介紹了Unity3D仿寫(xiě)B(tài)utton面板事件綁定功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02C#截取中英文混合指定長(zhǎng)度字符串實(shí)例
這篇文章主要介紹了C#截取中英文混合指定長(zhǎng)度字符串,大家參考使用2013-12-12Winform實(shí)現(xiàn)將網(wǎng)頁(yè)生成圖片的方法
這篇文章主要介紹了Winform實(shí)現(xiàn)將網(wǎng)頁(yè)生成圖片的方法,類(lèi)似于一般瀏覽器自帶的網(wǎng)頁(yè)生成圖片的功能,需要的朋友可以參考下2014-09-09WinForm之BindingSource基礎(chǔ)操作實(shí)例教程
這篇文章主要介紹了WinForm之BindingSource基礎(chǔ)操作,對(duì)BindingSource組建的用法進(jìn)行較為深入的實(shí)例分析,需要的朋友可以參考下2014-08-08