Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Margin Properties in code

Tags:

c#

margin

wpf

MyControl.Margin.Left = 10; 

Error:

Cannot modify the return value of 'System.Windows.FrameworkElement.Margin' because it is not a variable

like image 407
Giffyguy Avatar asked Jun 16 '09 20:06

Giffyguy


People also ask

How do you set margins in HTML code?

Definition and Usage Two values, like: div {margin: 50px 10px} - the top and bottom margins will be 50px, left and right margins will be 10px. Three values, like: div {margin: 50px 10px 20px}- the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px.

Which property is used to set the margin?

The margin-right property in CSS is used to set the right margin of an element. It sets the margin-area on the right side of the element. Negative values are also allowed. The default value of margin-right property is zero.

How can we set margins for an element?

Answer: You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

What is the correct HTML code for setting top margin?

margin: 10px 5px 15px 20px; top margin is 10px.


1 Answers

The problem is that Margin is a property, and its type (Thickness) is a value type. That means when you access the property you're getting a copy of the value back.

Even though you can change the value of the Thickness.Left property for a particular value (grr... mutable value types shouldn't exist), it wouldn't change the margin.

Instead, you'll need to set the Margin property to a new value. For instance (coincidentally the same code as Marc wrote):

Thickness margin = MyControl.Margin; margin.Left = 10; MyControl.Margin = margin; 

As a note for library design, I would have vastly preferred it if Thickness were immutable, but with methods that returned a new value which was a copy of the original, but with one part replaced. Then you could write:

MyControl.Margin = MyControl.Margin.WithLeft(10); 

No worrying about odd behaviour of mutable value types, nice and readable, all one expression...

like image 115
Jon Skeet Avatar answered Sep 28 '22 17:09

Jon Skeet