Setting Margin Properties in code

Giffyguy picture Giffyguy · Jun 16, 2009 · Viewed 132k times · Source
MyControl.Margin.Left = 10;

Error:

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

Answer

Jon Skeet picture Jon Skeet · Jun 16, 2009

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...