Difference between Canvas and Grid to Move, Resize

2019-06-07 19:35发布

问题:

I want to develop a editor that can add dynamically Controls and after to move, resize or rotate to build a window with this UIElements.

My question is who is better for a Container of this UIElements, a Grid or a Canvas?

Canvas are working in absolute position, maybe have better precision for transforming. But is less responsive when I will display the App in different screen resolutions? I doesn't know very well about the pros/cons from Grid or Canvas.

I made a example with a Canvas and Grid to move a UIElement with this code:

private void ui_MouseMove(object sender, MouseEventArgs e)
    {
        if (m_IsPressed)
        {
            UIElement ui = (UIElement)sender;
            TranslateTransform transform = new TranslateTransform();
            transform.X = Mouse.GetPosition(MyGridOrCanvas).X;
            transform.Y = Mouse.GetPosition(MyGridOrCanvas).Y;
            ui.RenderTransform = transform;
        }
    }

But with the Canvas or Grid, when I click the UIElement and without moving, the UIElement always moved x,y from my cursor. Maybe isn't the best way to do this. If you have also tutorials about how to build this features will help me too. I'm new with this stuff.

Thank you very much and greetings!

回答1:

I'll just provide a short answer for this question as it is likely to be closed by the community here for being too subjective. I can see one close vote already.

So, in my opinion, the Canvas is a much better control to use for this purpose. For one reason, it does not have the considerable layout requirements of the Grid and so it is more efficient. The other main reason is that using the Canvas.Top and Canvas.Left properties to move the items is perfect... to move items in other Panels, you often have to make do with setting the Margin property instead, which is far from ideal.

As for your items moving when being clicked on... that's just a bug in your code doing that, it's not the normal behaviour - a control won't move on its own unless we tell it to.