MAUI 创建一个简单的计算器应用
今天我们来创建一个简单的基于 MAUI 的计算器应用。
首先启动 Visual Studio 2022 ,然后创建一个 .NET MAUI 应用,


项目创建后我们可以直接进行运行,默认界面如下:

默认项目结构:

MainPage.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="calculator.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Image
Source="dotnet_bot.png"
SemanticProperties.Description="Cute dot net bot waving hi to you!"
HeightRequest="200"
HorizontalOptions="Center" />
<Label
Text="Hello, World!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
<Label
Text="Welcome to .NET Multi-platform App UI"
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome to dot net Multi platform App U I"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
程序需求
程序需要很简单,解释计算两个数字的加法计算,然后把结果显示出来。
首先我们需要两个输入框和一个显示结果的 Label,还需要一个按键。
这里我们用到了两个布局容器 VerticalStackLayout 和 HorizontalStackLayout,前一个是垂直布局,后一个是水平布局。
完成后的程序
MainPage.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="calculator.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="12"
Padding="22"
VerticalOptions="Center">
<HorizontalStackLayout
Spacing="12"
Padding="22"
HorizontalOptions="Center">
<Entry x:Name="num1"
Placeholder="输入一个数字" />
<Label VerticalOptions="Center"
Text="+"/>
<Entry x:Name="num2"
Placeholder="输入一个数字" />
<Label VerticalOptions="Center"
Text="="/>
<Button Clicked="OnGetResultClicked"
Text="计算"
SemanticProperties.Hint="点击计算结果" />
</HorizontalStackLayout>
<HorizontalStackLayout
Spacing="12"
Padding="22"
HorizontalOptions="Center"
VerticalOptions="Center">
<Label Text="结果:"/>
<Label x:Name="result"
TextColor="#c00"
Text="0"/>
</HorizontalStackLayout>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
MainPage.xaml.cs
namespace calculator;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnGetResultClicked(object sender, EventArgs e)
{
result.Text = (int.Parse(num1.Text) + int.Parse(num2.Text)).ToString();
}
}


浙公网安备 33010602011771号