I am looking for a way to define Thickness in Xaml based on application wide defined constants, e.g.
<StackLayout Margin="MSpace,SSpace,LSpace,MSpace">
<Label Text="Just an example"/>
</StackLayout>
where SSpace, MSpace and LSpace are constants defined once in the app.
If I was only dealing with my own custom controls only I could probably write my own TypeConverter (c# how to implement type converter) and decorate each property where appropriate with something like
[TypeConverter(typeof(ConstantStringToThicknessConverter))]
I don't think this is an option since I want to use my string of constants with any type of Maui layout. I am looking for a solution where everything is done in xaml with the exception of defining the constants.
Define Thickness in XAML Resources:
<x:Double x:Key="left">10</x:Double>
<x:Double x:Key="top">20</x:Double>
<x:Double x:Key="right">30</x:Double>
<x:Double x:Key="bottom">40</x:Double>
<Thickness x:Key="thickness"
Left="{StaticResource left}"
Top="{StaticResource top}"
Right="{StaticResource right}"
Bottom="{StaticResource bottom}"/>
Usage in XAML StackLayout:
<StackLayout Margin="{StaticResource thickness}" />
Thickness can also be used like this in a StackLayout Margin:
<StackLayout>
<StackLayout.Margin>
<Thickness Left="{StaticResource left}"
...
</StackLayout.Margin>
...
With constants:
namespace ConstantsNamespace
{
public static class Constants
{
public const double Left = 10;
...
Usage of constants in XAML Thickness:
xmlns:ns="clr-namespace:ConstantsNamespace;assembly=Constants.Assembly"
...
<Thickness Left="{x:Static ns:Constants.Left}"
...
Here's what I've been doing lately.
namespace MyApp.UI;
public static class UiConstants
{
public static readonly Thickness DefaultMargin = new Thickness(10, 10, 10, 10);
}
<ContentPage ...
xmlns:ui="clr-namespace:MyApp.UI">
<StackLayout Margin="{x:Static ui:UiConstants.DefaultMargin}">
<Label Text="Just an example"/>
</StackLayout>
</ContentPage>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With