Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a StackPanel and its contents "draggable" in wpf?

Tags:

c#

wpf

xaml

I have a UserControl in the form of:

<UserControl>   
    <Grid>         
          <!-- Content Here-->    
      <StackPanel>   <!-- I want this element to be draggable within the usercontrol. -->    
         <Label Name = "Header" />  
         <Button />
         <Button />
         <Button />             
         </StackPanel>    
   <Grid>             
</UserControl>

My end result is to have a control with buttons (part of the usercontrol) that can be dragged around..? That is, moveable ... within the UserControl

Ive read about Thumb but I am not sure how to use it...Any ideas or examples would be great.Thanks!

like image 526
user1202434 Avatar asked Dec 11 '22 22:12

user1202434


1 Answers

A very simple way to do it would be to use mouse events

First off, wrap your StackPanel in a Canvas so it can be easily positioned according to where the user drags it

Next, add MouseDown and MouseUp events to the StackPanel. You may need to give your StackPanel a background color for it to receive mouse events.

In the MouseDown event, attach a MouseMove event handler to the StackPanel and have the panel capture the mouse so all mouse events will get handled by the StackPanel.

In the MouseUp event, detach the MouseMove event and release your mouse capture.

In the MouseMove event, change the Canvas.Top and Canvas.Left properties of the panel based on the current Mouse position. You will need a check here to determine if the mouse is outside of the UserControl too so the StackPanel can't be dragged off screen.

And that's it, very basic drag drop :)

like image 81
Rachel Avatar answered Dec 14 '22 10:12

Rachel