Drag WPF Popup control


Question

the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)?

can this be done without big problems or do i have to write a substitute for the popup class myself? thanks

1
19
2/12/2009 3:38:37 PM

Accepted Answer

Here's a simple solution using a Thumb.

  • Subclass Popup in XAML and codebehind
  • Add a Thumb with width/height set to 0 (this could also be done in XAML)
  • Listen for MouseDown events on the Popup and raise the same event on the Thumb
  • Move popup on DragDelta

XAML:

<Popup x:Class="PopupTest.DraggablePopup" ...>
    <Canvas x:Name="ContentCanvas">

    </Canvas>
</Popup>

C#:

public partial class DraggablePopup : Popup 
{
    public DraggablePopup()
    {
        var thumb = new Thumb
        {
            Width = 0,
            Height = 0,
        };
        ContentCanvas.Children.Add(thumb);

        MouseDown += (sender, e) =>
        {
            thumb.RaiseEvent(e);
        };

        thumb.DragDelta += (sender, e) =>
        {
            HorizontalOffset += e.HorizontalChange;
            VerticalOffset += e.VerticalChange;
        };
    }
}
15
11/17/2011 4:26:23 PM

There is no DragMove for PopUp. Just a small work around, there is lot of improvements you can add to this.

<Popup x:Name="pop" IsOpen="True" Height="200" Placement="AbsolutePoint"  Width="200">
   <Rectangle Stretch="Fill" Fill="Red"/>            
</Popup>

In the code behind , add this mousemove event

   pop.MouseMove += new MouseEventHandler(pop_MouseMove);

   void pop_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            pop.PlacementRectangle = new Rect(new Point(e.GetPosition(this).X,
                e.GetPosition(this).Y),new Point(200,200));

        }
    }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon