Edward Tanguay Edward Tanguay - 7 months ago 66
C# Question

How to set a top margin only in XAML?

I can set margins individually in code but how do I do it in XAML, e.g. how do I do this:


<StackPanel Margin.Top="{Binding TopMargin}">


The key is to realize that setting it in code like this:

sp2.Margin = new System.Windows.Thickness{ Left = 5 };

is equivalent to:

sp2.Margin = new System.Windows.Thickness{ Left = 5, Top = 0, Right = 0, Bottom = 0 };

You can't set just a single value in a Thickness instance through either code or XAML. If you don't set some of the values, they will be implicitly zero. Therefore, you can just do this to convert the accepted code sample in your other question to a XAML equivalent:

<StackPanel Margin="{Binding TopMargin, Converter={StaticResource MyConverter}}"/>

where MyConverter just returns a Thickness that sets only the Top and leaves all other values as zero.

Of course, you could write your own control that does expose these individual values as dependency properties to make your code a little cleaner:

<CustomBorder TopMargin="{Binding TopMargin}">