6

I've got some custom controls which are dynamically added to a custom grid. These controls can span over several columns and rows(which are all the same size). I'd like to drag and drop between the rows and columns. I can drag the individual controls, but they can move anywhere without limit. Even off the grid. I'd like to do it so it can only be dragged inside the grid AND snaps to the column/row it's dragged to.

Is there any easy-ish way to do this?

Honestly, if I could get the current row/column that it's over, then all I'd need to do is set the column/row of it to them and that would probably do it and then just worry about keeping it inside the grid.

2
  • Something like this maybe: dotnetcurry.com/showarticle.aspx?ID=677?
    – zaitsman
    Aug 13, 2014 at 9:29
  • They're arbitrary controls, though. Though they're all subclassed from the same thing. I need more so the row/column of where I've dragged the item to.
    – Gentatsu
    Aug 13, 2014 at 9:44

2 Answers 2

5

I figured out a nice and fun way!

I worked out the position on the grid that the the mouse is on on the MouseUp event and then the relative position of the mouse on the control since it spans several rows/columns.

public void getPosition(UIElement element, out int col, out int row)
    {
        DControl control = parent as DControl;
        var point = Mouse.GetPosition(element);
        row = 0;
        col = 0;
        double accumulatedHeight = 0.0;
        double accumulatedWidth = 0.0;

        // calc row mouse was over
        foreach (var rowDefinition in control.RowDefinitions)
        {
            accumulatedHeight += rowDefinition.ActualHeight;
            if (accumulatedHeight >= point.Y)
                break;
            row++;
        }

        // calc col mouse was over
        foreach (var columnDefinition in control.ColumnDefinitions)
        {
            accumulatedWidth += columnDefinition.ActualWidth;
            if (accumulatedWidth >= point.X)
                break;
            col++;
        }
    }

I then take away the relative positions from the normal positions so that when you drop it, it always drops on the top left of the screen. When I move my controls, I use margins to move it, which screws up the position on the grid at the time, as shown below:

void Chart_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (IsMouseCaptured)
        {
            Point mouseDelta = Mouse.GetPosition(this);
            mouseDelta.Offset(-mouseOffset.X, -mouseOffset.Y);

            Margin = new Thickness(
                Margin.Left + mouseDelta.X,
                Margin.Top + mouseDelta.Y,
                Margin.Right - mouseDelta.X,
                Margin.Bottom - mouseDelta.Y);
        }

    }

    void Chart_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        mouseOffset = Mouse.GetPosition(this);
        CaptureMouse();
        parent.currentObject = this;
    }

To tackle this, I simply reset the margin.

public void updatePosition()
    {
        Grid.SetRow(this, (int)position.Y);
        Grid.SetColumn(this, (int)position.X);
        Margin = new Thickness();
    }

I hope this helps someone else since it was rather frustrating for me to find the answer and in the end I managed to get lots of little fragments of how to do things and eventually came up with my own solution.

3
  • The WPF ThumbControl should be capable of dealing with this without the Margin trick, but it doesn’t. After many, many fruitless hours with ThumbControls, I finally went your way, @Gentatsu. Nice job, well done.
    – Informagic
    Oct 2, 2017 at 12:28
  • What does parent refer to? What is a DControl? Aug 21, 2018 at 19:14
  • Could you post the whole code? Having problems to reproduce that.
    – Eych
    Mar 8, 2020 at 14:27
1

Is there any easy-ish way to do this?

I'd say that the answer to this question very much depends on your experience using Drag and Drop functionality... for a beginner, I'd say that the answer to this was no, but for someone with some experience and some common sense, it might not be too bad.

To determine which Grid cell the user's mouse is over will not be straight forward. You can handle the PreviewDragOver event and use the VisualTreeHelper.HitTest method to check which control the mouse is currently over:

private void PreviewDragOver(object sender, DragEventArgs e)
{
    HitTestResult hitTestResult = VisualTreeHelper.HitTest(adornedUIElement, 
        e.GetPosition(adornedUIElement));
    Control controlUnderMouse = hitTestResult.VisualHit.GetParentOfType<Control>();
}

The GetParentOfType method is a useful extension method that I created, but you can convert it to a normal method easily enough:

public static T GetParentOfType<T>(this DependencyObject element) where T : DependencyObject
{
    Type type = typeof(T);
    if (element == null) return null;
    DependencyObject parent = VisualTreeHelper.GetParent(element);
    if (parent == null && ((FrameworkElement)element).Parent is DependencyObject) parent = ((FrameworkElement)element).Parent;
    if (parent == null) return null;
    else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) return parent as T;
    return GetParentOfType<T>(parent);
}

Of course, once you have a Control in your controlUnderMouse variable, you'll still have some considerable work to do as you work your way through the UIElements until you get to the Grid... you can of course make further use of the GetParentOfType method to make your job easier.

4
  • I managed to get the position of the mouse at the current grid by counting the row height + column widths until it hits the mouse point. I then work out the relative position of my mouse to the top left corner of my control and take it off the position so it assigns it to that. It gets the correct values but when I do Grid.SetRow(this, row) on the item and likewise with Grid.SetColumn it puts them in a random-ish place. Is there any reason for that? Is it because it moves the control using margins?
    – Gentatsu
    Aug 13, 2014 at 10:48
  • Welp, yes it is. When I update them, I reset the margin and it works great! I'm not sure why I'm commenting on this answer since I didn't use anything from it, but thanks for helping me anyway!
    – Gentatsu
    Aug 13, 2014 at 10:49
  • I'm not sure why I'm commenting on this answer... neither do I. Add your solution into an answer and accept it when you can.
    – Sheridan
    Aug 13, 2014 at 10:58
  • Sorry about that! I've done that, but I'm not allowed to accept it for a couple days, unfortunately.
    – Gentatsu
    Aug 13, 2014 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.