1

I can set the margin of a stackpanel in code-behind like this:

StackPanel sp2 = new StackPanel();
sp2.Margin = new System.Windows.Thickness(5);

But how can I set each individually, both of these don't work:

PSEUDO-CODE:

sp2.Margin = new System.Windows.Thickness("5 0 0 0");
sp2.Margin.Left = new System.Windows.Thickness(5);
Arcturus
  • 26,677
  • 10
  • 92
  • 107
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

2 Answers2

9

You can also try this:

sp2.Margin = new System.Windows.Thickness{ Left = 5 };
Arcturus
  • 26,677
  • 10
  • 92
  • 107
5

Margin is of type Thickness which is a structure.

The parsing of "5 0 0 0" is a XAML thing, its not something that Thickness constructor handles.

Use

sp2.Margin = new System.Windows.Thickness(5,0,0,0);

since Thickness is a structure this should also work, leaving the other margin values unmodified:-

sp2.Margin.Left = 5;
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • Does your last line actually leave the rest unmodified? [This Answer](https://stackoverflow.com/a/1316649/2550406) claims otherwise – lucidbrot Apr 16 '19 at 08:40