Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants for Thickness

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.

like image 337
Mouse On Mars Avatar asked Mar 30 '26 14:03

Mouse On Mars


2 Answers

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}"
           ...
like image 70
Benl Avatar answered Apr 03 '26 17:04

Benl


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>
like image 38
Michal Diviš Avatar answered Apr 03 '26 15:04

Michal Diviš