WPF Margin demystified.
Posted by Vadim on October 13, 2008
In my previous post I asked a question about this line of code:
In XAML we can assign margin to a control three different ways:
- The first line assigns left, top, right, and bottom margins with value 5.
- The second line assigns left and right margins with value 10 but top and bottom with value 5.
- The last line assigns left, right, and bottom with value 10 and top would have value 5.
If we try to do the same in the code behind, it would look like this:
You can see in the code above that we have code for line 1 & 3 only. I couldn’t find the way to create code behind for second line because there’s no Thickness constructor with two parameters.
After I read Sam’s comment:
The converter at work here is a ThicknessConverter which parses the input string and attempts to map the values given in the string to one of the Thickness object constructor overloads.
, I used .NET Reflector to analyze ThicknesseConverter class.
ThicknesseConveter has a public method ConvertFrom that calls internal method FromString.
FromString method is responsible for parsing string values like “10, 5, 10, 10” and converting them into Thickness.
It means that this code
will be converted by FromString method into:
Bellow is a switch statement in FromString method that explains the magic.
If you want to assign a margin with two doubles from the code behind, you can do it like this:
Mystery is solved.