Wednesday, June 29, 2022

Maui sample code and its equivalent from the code behind.

Maui sample code and its equivalent from the code behind. 

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class="Phoneword.MainPage">

    <ScrollView>

        <VerticalStackLayout>

            <Label Text="Current count: 0"

                FontSize="18"

                FontAttributes="Bold"

                x:Name="CounterLabel"

                HorizontalOptions="Center" />

               <Button Text="Click me"

                Grid.Row="1"

                Clicked="OnCounterClicked"

                HorizontalOptions="Center" />

        </VerticalStackLayout>

    </ScrollView>

</ContentPage>

The equivalent code in C# looks like this:

public partial class TestPage : ContentPage

{

    int count = 0;

    // Named Label - declared as a member of the class

    Label counterLabel;

    public TestPage()

    {       

        var myScrollView = new ScrollView();

        var myStackLayout = new VerticalStackLayout();

        myScrollView.Content = myStackLayout;

        counterLabel = new Label

        {

            Text = "Current count: 0",

            FontSize = 18,

            FontAttributes = FontAttributes.Bold,

            HorizontalOptions = LayoutOptions.Center

        };

        myStackLayout.Children.Add(counterLabel);    

        var myButton = new Button

        {

            Text = "Click me",

            HorizontalOptions = LayoutOptions.Center

        };

        myStackLayout.Children.Add(myButton);


        myButton.Clicked += OnCounterClicked;


        this.Content = myScrollView;

    }


    private void OnCounterClicked(object sender, EventArgs e)

    {

        count++;

        counterLabel.Text = $"Current count: {count}";


        SemanticScreenReader.Announce(counterLabel.Text);

    }

}

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...