Skip to content
Home » Basics of .NET MAUI – Part 7 – Objects and Properties in C# Code

Basics of .NET MAUI – Part 7 – Objects and Properties in C# Code

Spread the love

So far in the series we’ve been creating objects and properties mostly in XAML. But sometimes you may have to create an object in C# code. Or maybe you don’t want to use XAML at all… This is also possible. In this part of the series we’ll be creating objects, like views and layouts, in C# and we’ll be setting their properties in C#.

The source code for this article is available on Github.

Creating objects in C# requires from you that you know what type the properties are. You can figure it out from documentation. To make things clearer, we’ll be comparing XAML code with C# code so that you can immediately see what corresponds to what. Actually, we’ll still be using some XAML here, because we can easily mix and match. So, open your TestPage.xaml and TestPage.xaml.cs pages and get ready.

Creating Views in C#

To start with, let’s rewrite the TestPage.xaml file to look like so:

<?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"
             x:Class="Slugrace.TestPage"
             Title="TestPage">
    <VerticalStackLayout x:Name="layout">
        <Label 
            Text="Test Page"
            VerticalOptions="Center" 
            HorizontalOptions="Center" 
            TextColor="Blue"
            FontSize="60"
            FontAttributes="Bold, Italic" 
            Rotation="180"
            CharacterSpacing="20"
            TranslationY="100" />
    </VerticalStackLayout>
</ContentPage>

If you run it on Android, you will see a fancy label:

And now let’s remove the label from the XAML file (still leaving the VerticalStackLayout in place):

<?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"
             x:Class="Slugrace.TestPage"
             Title="TestPage">
    <VerticalStackLayout x:Name="layout" />
</ContentPage>

Now we’ll create it in C#. We’ll also add it to the VerticalStackLayout in C# code. So, open your TestPage.xaml.cs file and make sure it looks like this:

using Microsoft.Maui.Platform;

namespace Slugrace;

public partial class TestPage : ContentPage
{    
    public TestPage()
	{
		InitializeComponent();

        Label label = new()
        {
            Text = "Hey",
            HorizontalOptions = LayoutOptions.Center,
            TextColor = Colors.Blue,
            FontSize = 60,
            FontAttributes = FontAttributes.Bold | FontAttributes.Italic,
            Rotation = 180,
            CharacterSpacing = 10,
            TranslationY = 100
        };

        layout.Add(label);
    }       
}

And now let’s remove the label and create a button with a click event. First, let’s do it in XAML:

<?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"
             x:Class="Slugrace.TestPage"
             Title="TestPage">
    <VerticalStackLayout x:Name="layout">
        <Button
            Text="Click" 
            FontSize="24"
            WidthRequest="200"
            Margin="50"
            BorderColor="Black"
            BorderWidth="5"
            BackgroundColor="DarkGoldenrod"
            TextTransform="Uppercase"
            FontAttributes="Bold"
            CornerRadius="50"
            Clicked="Button_Clicked" />
    </VerticalStackLayout>
</ContentPage>

This will produce the following button:

There’s a Clicked event that we could implement like this in the code-behind:

using Microsoft.Maui.Platform;

namespace Slugrace;

public partial class TestPage : ContentPage
{    
    public TestPage()
	{
		InitializeComponent();        
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        (sender as Button).Text = "Clicked";
    }
}

If you now click the button,  the text on it will change. So, here you can see some properties and an event. Let’s remove the button from the XAML file, this time along with the VerticalStackLayout, and we’ll recreate both the layout and the view in C#. The XAML file should look like so:

<?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"
             x:Class="Slugrace.TestPage"
             Title="TestPage">    
</ContentPage>

And here’s the C# file:

using Microsoft.Maui.Platform;

namespace Slugrace;

public partial class TestPage : ContentPage
{    
    public TestPage()
	{
		InitializeComponent();

        // create layout
        VerticalStackLayout layout = new();

        // create view
        Button button = new()
        {
            Text = "Click",
            FontSize = 24,
            WidthRequest = 200,
            Margin = 50,
            BorderColor = Colors.Black,
            BorderWidth = 5,
            BackgroundColor = Colors.DarkGoldenrod,
            TextTransform = TextTransform.Uppercase,
            FontAttributes = FontAttributes.Bold,
            CornerRadius = 50
        };

        // add event
        button.Clicked += Button_Clicked;

        // add view to layout
        layout.Add(button);

        // set layout as the page's content
        Content = layout;
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        (sender as Button).Text = "Clicked";
    }    
}

So far we’ve been creating simple objects and adding them to the layout. We also created a layout in C# code and set it as the page’s content. Next, let’s create a more complex layout with some children that use attached properties and see how to recreate it in C# code.

Creating Layouts and Attached Properties in C#

A good example of a more complex layout that we can use to demonstrate how attached properties are defined in C# code is the Grid. So, let’s define a Grid in XAML and add some children to it. Remove all the button-related code from both test files and create the Grid in the XAML file like so:

<?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"
             x:Class="Slugrace.TestPage"
             Title="TestPage">
    <Grid 
        Margin="40" 
        BackgroundColor="OldLace" 
        RowSpacing="10"
        ColumnSpacing="10"
        RowDefinitions="100, *"
        ColumnDefinitions="*, 2*" >
        <BoxView Color="Red" />
        <BoxView Grid.Column="1" Color="Green" />
        <BoxView Grid.Row="1" Grid.ColumnSpan="2" Color="Blue" />
    </Grid>
</ContentPage>

Run the app and you will see three BoxViews:

Next, remove the Grid from the XAML file and define it in C# code. The XAML file should now contain just the ContentPage. Watch how the Grid.Row, Grid.Column and Grid.ColumnSpan attached properties are set in C#. Also watch how the rows and columns are defined:

using Microsoft.Maui.Platform;

namespace Slugrace;

public partial class TestPage : ContentPage
{    
    public TestPage()
	{
		InitializeComponent();

        // create grid
        Grid grid = new()
        {
            Margin = 40,
            BackgroundColor = Colors.OldLace,
            RowSpacing = 10,
            ColumnSpacing = 10,
            RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(100) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }
            },
            ColumnDefinitions =
            {
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                new ColumnDefinition { Width = new GridLength(2, GridUnitType.Star) }
            }            
        };

        // add children to grid

        // Row 0 and Column 0 are the default values, so we can leave them out.
        grid.Add(new BoxView 
        { 
            Color = Colors.Red 
        });

        // We can pass the column (1) and the row (0) as arguments to the Add method.
        grid.Add(new BoxView
        {
            Color = Colors.Green
        }, 1, 0);

        // Alternatively, we can position the child with the Grid.SetRow and
        // Grid.SetColumn methods (we don't need the latter in this example
        // because the default value of 0 is used). There are also the Grid.RowSpan
        // (not used here) and Grid.ColumnSpan methods.
        BoxView blueBox = new BoxView { Color = Colors.Blue };
        Grid.SetRow(blueBox, 1);
        Grid.SetColumnSpan(blueBox, 2);
        grid.Add(blueBox);

        // set page content
        Content = grid;
    }
}

If you work with other attached properties, just check out in the documentation how to use them in code.

Naturally, there’s much more to XAML. What we’ve covered so far is just a tiny fraction of what there is, but we are now ready to design the pages for our Slugrace project, so let’s leverage the knowledge we just gained to do right that. And no worries… We’ll be learning lots of new XAML concepts on the way.


Spread the love
Tags:

Leave a Reply