A draggable popup control in wpf

后端 未结 2 1520
天涯浪人
天涯浪人 2021-01-03 04:46

I need a draggable popup control in wpf and was wondering if any of your guys could help me out..I did see the following post:

Drag WPF Popup control

but tha

2条回答
  •  迷失自我
    2021-01-03 05:44

    We can write a behavior to make any Popup draggable. Here is some sample XAML of a popup associated with a textbox that opens and stays open when the text box is focused:

    
        
            
        
        
            
                
            
            
                Sample Popup content.
            
        
    
    

    Here is the behavior that allows us to drag the Popup:

    public class MouseDragPopupBehavior : Behavior
    {
        private bool mouseDown;
        private Point oldMousePosition;
    
        protected override void OnAttached()
        {
            AssociatedObject.MouseLeftButtonDown += (s, e) =>
            {
                mouseDown = true;
                oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
                AssociatedObject.Child.CaptureMouse();
            };
            AssociatedObject.MouseMove += (s, e) =>
            {
                if (!mouseDown) return;
                var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
                var offset = newMousePosition - oldMousePosition;
                oldMousePosition = newMousePosition;
                AssociatedObject.HorizontalOffset += offset.X;
                AssociatedObject.VerticalOffset += offset.Y;
            };
            AssociatedObject.MouseLeftButtonUp += (s, e) =>
            {
                mouseDown = false;
                AssociatedObject.Child.ReleaseMouseCapture();
            };
        }
    }
    

    If you are not familiar with behaviors, install the Expression Blend 4 SDK and add this namespaces:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    

    and add System.Windows.Interactivity to your project.

提交回复
热议问题