In fact, it is very easy to support drag and drop in wpf. You can use drag events or custom mouse events.
Today, we will share a drag-and-drop slide effect with mouse clicks and up events.
First, define a ScrollViewer in xaml.
| The code is as follows: |
Copy code |
<Window x: Class = "Wpf drag/drop sliding effect. MainWindow"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "400" Width = "680">
<Grid>
<ScrollViewer Name = "viewer" Grid. Column = "0" Grid. Row = "1" Padding = "0, 0, 0" VerticalScrollBarVisibility = "Auto">
<Canvas Name = "canvas" Margin = "0, 0, 0" PreviewMouseDown = "canvas_PreviewMouseDown" PreviewMouseMove = "canvas_PreviewMouseMove" PreviewMouseUp = "canvas_PreviewMouseUp">
<Grid Name = "NGEntry">
</Grid>
</Canvas>
</ScrollViewer>
</Grid>
</Window>
|
Simulate button data in the background:
| The code is as follows: |
Copy code |
/// <Summary>
/// Create a button set
/// </Summary>
/// <Param name = "grid"> </param>
Public void CreateNgEtry (ref Grid grid)
{
Grid. Children. Clear ();
Grid. RowDefinitions. Clear ();
Grid. ColumnDefinitions. Clear ();
For (int I = 0; I <6; I ++)
{
}
For (int I = 0; I <18 + 1; I ++)
{
Grid. RowDefinitions. Add (new RowDefinition ());
}
For (int I = 0; I <18; I ++)
{
Grid. ColumnDefinitions. Add (new ColumnDefinition ());
For (int j = 0; j <6; j ++)
{
Button but = new Button ();
But. Height = 80;
But. Width = 110;
But. FontSize = 16;
Grid. Children. Add ();
System. Windows. Controls. Grid. SetColumn (but, j );
System. Windows. Controls. Grid. SetRow (but, I );
But. Content = "Test" + I. ToString ();
}
}
}
|
Handle the event when you press the mouse, and remember the current position:
| The code is as follows: |
Copy code |
Private void canvas_PreviewMouseDown (object sender, MouseButtonEventArgs e)
{
TargetElement = Mouse. DirectlyOver as UIElement;
If (targetElement! = Null)
{
TargetPoint = e. GetPosition (NGEntry );
}
}
|
When dragging the mouse:
| The code is as follows: |
Copy code |
Private void canvas_PreviewMouseMove (object sender, MouseEventArgs e)
{
If (e. LeftButton = MouseButtonState. Pressed & targetElement! = Null)
{
Var pCanvas = e. GetPosition (canvas );
Double gridtop = Convert. ToDouble (NGEntry. GetValue (Canvas. TopProperty ));
NGEntry. SetValue (Canvas. TopProperty, pCanvas. Y-targetPoint. Y );
}
}
|
When you move the mouse down the event:
| The code is as follows: |
Copy code |
|
Private void canvas_PreviewMouseUp (object sender, MouseButtonEventArgs e)
{
Double gridtop = Convert. ToDouble (NGEntry. GetValue (Canvas. TopProperty ));
Double gridh = NGEntry. ActualHeight;
Double viewh = canvas. ActualHeight;
If (gridtop> 0)
{
NGEntry. SetValue (Canvas. TopProperty, 0d );
}
If (viewh + (Math. Abs (gridtop)> gridh)
{
NGEntry. SetValue (Canvas. TopProperty, viewh-gridh );
}
} |