xamlwindows-8margin

XAML: Is there some ways that I could declare a variable for Margin property?


I want to declare a variable for Margin value like this:

<x:MarginStruct x:Key="myMargin1">10,5,20,20</x:MarginStruct>

then I could reuse this resource value for some UI elements like this:

<TextBlock Margin={StaticResource myMargin1}">text1</TextBlock>
<TextBlock Margin={StaticResource myMargin1}">text2</TextBlock>

Should I define a class/struct MarginStruct with four double members?

If that is a way, what if margin value likes "10,5" or "10" in some situations, how should we handle it?

Thanks! Any ideas is appreciated!


Solution

  • You can declare this resource:

    <Thickness x:Key="MyMargin" Left="10" Top="5" Right="20" Bottom="20" /> and then use this:

    <TextBlock Margin="{StaticResource MyMargin}">text1</TextBlock>