DEV Community

Janki Mehta
Janki Mehta

Posted on

Add styles with CSS to .NET MAUI app

Adding styles with CSS to a .NET MAUI (Multi-platform App UI) app involves a few steps. CSS styles can help you define the visual appearance of your app's user interface. Here's how you can do it:

  • Create a CSS File: Start by creating a CSS file that will contain your styles. You can name it something like styles.css.
  • Add Styles to the CSS File: Open the styles.css file and add your CSS styles. For example:
.myButton { 
    background-color: blue; 
    color: white; 
    padding: 10px 20px; 
    border: none; 
    border-radius: 5px; 
} 
Enter fullscreen mode Exit fullscreen mode

In this example, a class .myButton is defined with specific styles for buttons.

  • Link the CSS File to Your App: In your .NET MAUI project, you need to link the CSS file to your XAML pages.
<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:local="clr-namespace:YourNamespace" 
             x:Class="YourNamespace.MainPage" 
             BackgroundStyle="BodyStyle"> 
    <ContentPage.Styles> 
        <Style x:Key="BodyStyle"> 
            <Style.BasedOn> 
                <local:CssStyleResource ResourceId="styles.css" /> 
            </Style.BasedOn> 
        </Style> 
    </ContentPage.Styles> 

    <!-- Your page content here --> 
</ContentPage>
Enter fullscreen mode Exit fullscreen mode

Replace YourNamespace with your actual namespace. In this example, the BodyStyle key is associated with the linked CSS file.

  • Create a CSS Style Resource Class: Create a class in your project that derives from CssStyleResource. This class will help load the CSS file.
using Microsoft.Maui.Controls; 

namespace YourNamespace 
{ 
    public class CssStyleResource : Style 
    { 
        public CssStyleResource() 
        { 
            this.ApplyStyleFromResource("/YourNamespace.styles.css"); 
        } 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

Replace /YourNamespace.styles.css with the correct path to your CSS file.

  • Apply Styles to Controls: To apply styles to controls in your XAML pages, use the StyleClass property.
<Button Text="Click Me" StyleClass="myButton" /> 

Enter fullscreen mode Exit fullscreen mode

The StyleClass property should match the class name you defined in your CSS file.

  • Build and Run: Build and run your .NET MAUI app. The CSS styles should be applied to the controls according to the classes you specified.

Remember to adjust the namespaces and paths according to your project structure. This example provides a basic overview of adding CSS styles to a .NET MAUI app. You can expand upon this foundation by adding more styles and customizing the appearance of your app's UI elements.

Top comments (0)