Home > Software engineering >  Maui/Xamarin.Forms: Apply properties on all Frames & Labels
Maui/Xamarin.Forms: Apply properties on all Frames & Labels

Time:03-17

So I make the following labels and frames:

//Frames
        private readonly Frame _frame1 = new Frame
        {
            BorderColor = Colors.Black,
            Padding = new Thickness(1),
            BackgroundColor = Colors.Gray
        };
        private readonly Frame _frame2 = new Frame
        {
            BorderColor = Colors.Black,
            Padding = new Thickness(1),
            BackgroundColor = Colors.Gray
        };
        private readonly Frame _frame3 = new Frame
        {
            BorderColor = Colors.Black,
            Padding = new Thickness(1),
            BackgroundColor = Colors.Gray
        };
//Labels
        private readonly Label _label1 = new Label
        {
            FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
            TextColor = Colors.Black,
            Padding = 5
        };
        private readonly Label _label2 = new Label
        {
            FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
            TextColor = Colors.Black,
            Padding = 5
        };
        private readonly Label _label3 = new Label
        {
            FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
            TextColor = Colors.Black,
            Padding = 5
        };

As you can see, I am setting stuff like textcolors, paddings and background colors multiple times when I am making a new label. I think this can be made a bit prettier by defining all those properties on a "standard" label/frame (not sure what the correct word for this is). But basically, when I use a frame or a label I always want these properties to apply.

Anyone know how to do this? I hope you will understand what I am trying to achieve haha, thanks in advance!

CodePudding user response:

Implicit styles are one way to go. In your App.xaml file:

<Application.Resources>
    <ResourceDictionary>
       <Style TargetType="Frame">
          <Setter Property="BorderColor" Value="Black" />
          <Setter Property="BackgroundColor" Value="Gray" />
          <Setter Property="Padding" Value="1" />
        </Style>
        <Style TargetType="Label">
           <Setter Property="FontSize" Value="Small" />
           <Setter Property="TextColor" Value="Black" />
           <Setter Property="Padding" Value="5" />
        </Style>
    </ResourceDictionary>
</Application.Resources>

Setting it this will automatically apply the styles to all Frames and Labels in the app.

Reference: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/xaml/implicit

  • Related