2022. 6. 29. 00:00ㆍMAUI
XAML(eXtensible Application Markup Language)은 개체를 인스턴스화 및 초기화하고
부모-자식 계층 구조에서 개체를 구성하기 위한 프로그래밍 코드 대신 사용할 수 있는 XML 기반 언어
XAML을 사용하면 개발자가 코드가 아닌 태그를 사용하여
.NET 다중 플랫폼 앱 UI(.NET MAUI) 앱에서 사용자 인터페이스를 정의할 수 있다.
.NET MAUI 앱에는 XAML이 필요하지 않지만, 간결하고 시각적으로 일관되며
도구 지원이 있는 경우가 많기 때문에 UI를 개발하는 것이 좋다.
XAML은 XAML 기반 데이터 바인딩을 통해 viewmodel 코드에 연결된 뷰를 정의하는
MVVM(Model-View-ViewModel) 패턴에도 적합
MAUI 에서 XAML 은 주로 페이지의 시각적 콘텐츠를 정의 하는데 사용되며 C# 코드 숨김 파일과 함께 작동
프로젝트 구조
App.xaml
XAML 레이아웃에서 사용할 애플리케이션 리소스를 정의 ,기본 리소스는 Resources 폴더에 있다.
.NET MAUI의 모든 기본 제공 컨트롤에 대한 앱 전체 색상 및 기본 스타일을 정의
여기에서 두 개의 리소스 사전이 병합되는 것을 볼 수 있다.
<?xml version = "1.0" encoding = "UTF-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyMauiApp"
x:Class="MyMauiApp.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
App.xaml.cs
런타임 시 애플리케이션을 나타내고 생성자는 초기 창을 만들고 MainPage 속성에 할당
MainPage 속성은 응용 프로그램 실행이 시작될 때 표시되는 페이지를 결정
이 클래스에서 애플리케이션 수명 주기 이벤트 처리기를 재정의할 수 있다.
이벤트에는 OnStart, OnResume 및 OnSleep이 포함된다.
using System.Diagnostics;
namespace MauiApp1;
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
protected override void OnStart()
{
Debug.Print("OnStart");
base.OnStart();
}
protected override void OnResume()
{
Debug.Print("OnResume");
base.OnResume();
}
protected override void OnSleep()
{
Debug.Print("OnSleep");
base.OnSleep();
}
}
AppShell.xaml
.NET MAUI 응용 프로그램의 기본 구조
.NET MAUI 셸은 앱 스타일 지정, URI 기반 탐색, 플라이아웃 탐색
애플리케이션 루트에 대한 탭을 포함한 레이아웃 옵션을 포함
기본 템플릿은 앱이 시작될 때 확장되는 단일 페이지(또는 ShellContent)를 제공
ShellContent 의 ContentTemplate 을 통해 MainPage.xaml 과 연결한다.
Route 경로는 MainPage 로 설정한다. 이 이름을 통해서 접근 가능하다.
결과적으로 MainPage.xaml 이 초기에 load 된다.
MainPage.xaml
이 파일에는 사용자 인터페이스 정의가 포함되어 있다.
MAUI 앱 템플릿으로 생성된 샘플 앱은 세 개의 레이블, 버튼 및 이미지로 구성된다.
컨트롤은 ScrollView에 포함된 VerticalStackLayout을 사용하여 정렬된다.
VerticalStackLayout 컨트롤은 컨트롤이 수직으로(스택에서) 정렬되도록 하고,
보기가 너무 커서 장치에 표시할 수 없는 경우 ScrollView는 스크롤 막대를 제공한다.
의도는 이 파일의 내용을 고유한 UI 레이아웃으로 바꾸는 것이다.
다중 페이지 앱이 있는 경우 더 많은 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="MauiApp1.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>
Button 은 behind code 인 MainPage.xaml.cs 에 OnCounterClicked 를 Handler method 로 두고 있다.
Click 시 해당 method 로 이동하고 로직을 처리 한다.
SenamticScreenReader.Announce 는 화면 판독기가 사용자에게 텍스트를 알리도록 지시 한다.
MauiProgram.cs
각 기본 플랫폼에는 응용 프로그램을 만들고 초기화하는 다른 시작점이 있다.
이 코드는 프로젝트의 Platforms 폴더에서 찾을 수 있다.
플랫폼에 따라 다르지만 MauiProgramclass의 CreateMauiApp 메서드를 호출한다.
CreateMauiApp 메서드를 사용하여 앱 빌더 개체를 만들어 애플리케이션을 구성한다.
최소한 애플리케이션을 설명하는 클래스를 지정해야 한다.
앱 빌더 개체의 UseMauiApp 일반 메서드를 사용하여 이 작업을 수행한다.
유형 매개변수는 애플리케이션 클래스를 지정한다.
앱 빌더는 다음과 같은 작업을 위한 메서드 제공
- 글꼴 등록,
- 종속성 주입을 위한 서비스 구성,
- 컨트롤에 대한 사용자 지정 처리기 등록
다음 코드는 앱 빌더를 사용하여 글꼴을 등록하는 예를 보여준다.
namespace MauiApp1;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
return builder.Build();
}
}
Platforms 폴더
이 폴더에는 플랫폼별 초기화 코드 파일과 리소스가 들어 있다.
Android, iOS, MacCatalyst 및 Windows용 폴더가 있다.
런타임 시 앱은 플랫폼별 방식으로 시작된다.
시작 프로세스의 대부분은 MAUI 라이브러리의 내부에 의해 추상화되지만
이러한 폴더의 코드 파일은 사용자 정의 초기화를 연결하기 위한 메커니즘을 제공한다.
중요한 점은 초기화가 완료되면 플랫폼별 코드가 MauiProgram.CreateMauiApp 메서드를 호출한 다음
앞에서 설명한 것처럼 App 개체를 만들고 실행한다는 것이다.
재정의가 포함되어 있는 폴더의 파일
- Android 폴더의 MainApplication.cs 파일
- iOS 및 MacCatalyst 폴더의 AppDelegate.cs 파일
- Windows 폴더의 App.xaml.cs 파일
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
프로젝트 리소스(Resources)
주 프로젝트의 .csproj 파일에는 몇 가지 주목할만한 섹션이 포함되어 있습니다.
초기 PropertyGroup
애플리케이션 제목,
ID,
버전,
디스플레이 버전
지원되는 운영 체제
프로젝트가 대상으로 하는 플랫폼 프레임워크를 지정
필요에 따라 이러한 속성을 수정할 수 있다.
<PropertyGroup>
<TargetFrameworks>net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net6.0-windows10.0.19041.0</TargetFrameworks>
<!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
<!-- <TargetFrameworks>$(TargetFrameworks);net6.0-tizen</TargetFrameworks> -->
<OutputType>Exe</OutputType>
<RootNamespace>MauiApp1</RootNamespace>
<UseMaui>true</UseMaui>
<SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Display name -->
<ApplicationTitle>MauiApp1</ApplicationTitle>
<!-- App Identifier -->
<ApplicationId>com.companyname.mauiapp1</ApplicationId>
<ApplicationIdGuid>124ACC44-C790-4EC9-8E04-6CF9B13E0CDC</ApplicationIdGuid>
<!-- Versions -->
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">14.2</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">14.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
</PropertyGroup>
초기 속성 그룹 아래의 ItemGroup 섹션을 사용하면
첫 번째 창이 표시되기 전에 앱이 로드되는 동안 표시되는
시작 화면의 이미지와 색상을 지정할 수 있다.
앱에서 사용하는 글꼴, 이미지 및 자산의 기본 위치를 설정할 수도 있다.
<ItemGroup>
<!-- App Icon -->
<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />
<!-- Splash Screen -->
<MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />
<!-- Images -->
<MauiImage Include="Resources\Images\*" />
<MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />
<!-- Custom Fonts -->
<MauiFont Include="Resources\Fonts\*" />
<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
솔루션 탐색기 창에서 리소스 폴더를 확장하면 이러한 항목을 확인 할 수 있다.
관련영상
'MAUI' 카테고리의 다른 글
.NET MAUI - XAML 의 동작방식 (0) | 2022.07.04 |
---|---|
.NET MAUI - Controls and Layouts (0) | 2022.07.01 |
.NET MAUI - Add page content (0) | 2022.06.30 |
.NET MAUI - Architecture (0) | 2022.06.28 |
.NET MAUI - Create Project (0) | 2022.06.27 |