Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Canvas Property and Margin

Tags:

c#

.net

wpf

There are any differences between using SetValue with (for example) Canvas.LeftProperty and Margin Property?

To be more clear:

<Canvas>
   <Rectangle x:Name="rect">                         
</Canvas>

Is

rect.SetValue(Canvas.LeftProperty, 10)

equivalent to

rect.Margin = new Thickness(10, 0, 0, 0)

or not?

like image 389
Nick Avatar asked Jun 13 '12 15:06

Nick


People also ask

What is margin in WPF?

The margin property in WPF allows you set spacing between elements in a window. You can assign the margins for the Top, Right, Bottom and Left. Every control that derives from FrameworkElement has this property.

What is Canvas padding?

Padding is space between a border and an object. Margin is space outside a border.

What is padding in WPF?

Padding represents the distance between the side of the control (which can be the margin) and its content. The content depends on the type of the control. Margin is outside the UI element, while Padding is inside it.


2 Answers

The Margin property is used with every element to determine extra space around the object. It works in almost all types of layouting (StackPanel, Grid, ContentControls, etc.)

The Canvas.LeftProperty (as well as Top, Right, and Bottom) only apply to elements which are directly inside a Canvas. The Canvas will use these values to determine where an object should be. With Shape elements like a Path, the Canvas also looks at the location data of the Shape when determining the position.

Technically, the Canvas attached properties should accumulate with the inherent location data of a Shape (if any) as well as the Margin. You could use all 3 to modify the position. But usually you would try to keep it simple.

For example, a Rectangle should use its Width and Height properties as well as Canvas.Left and Canvas.Top. A Path would either just rely on its point data or it would offset it with Canvas.Left and Canvas.Top. You shouldn't use margin for elements inside a Canvas since you have better control without using it, but you technically could.

like image 91
Trevor Elliott Avatar answered Sep 16 '22 12:09

Trevor Elliott


For an element directly in a Canvas, the only difference is in the means. The end result is exactly the same.

When the Rectangle is positioned, the layout engine will add together all the values that affect its position. For the X coordinate this includes Canvas.Left and Margin.Left.

So in one case it is adding 10 + 0, and in the other it is adding 0 + 10.

So go with whichever you prefer. Personally I prefer Canvas.Left in this situation as it seems to make more contextual sense.

like image 23
Ross Avatar answered Sep 18 '22 12:09

Ross