Microsoft MVP성태의 닷넷 이야기
Phone: 11. Xamarin.Forms - 2. XAML을 이용한 페이지 개발 [링크 복사], [링크+제목 복사],
조회: 15843
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
[Part1_2.zip]    

Xamarin.Forms - 2. XAML을 이용한 페이지 개발

이번에도 역시 "Xamarin.Forms - 1. Forms 시작하기" 글의 모델이었던 원본 시리즈의 2번째 글을 참고해서 작성한 것입니다. (거의 배꼈다고 보시면 됩니다. ^^)

Learning Xamarin: Forms and XAML
; http://blog.falafel.com/Blogs/jesse-liberty/2014/06/13/learning-xamarin-forms-and-xaml




"Xamarin.Forms - 1. Forms 시작하기" 글에서 UI를 코드로 작성했는데요. 그것만 보면 별로 매력이 별로 없을 텐데, 다행히 Xamarin은 WPF의 XAML을 최대한의 호환을 유지하며 Xamarin.Forms에 녹아냈습니다. 그것이 훌륭하지요. ^^

그래서, 지난번에 작성했던 MonkeyPage나 DetailPage를 코드가 아닌 XAML로 표현하는 것이 가능합니다. 바로 이것이 이번 글의 실습 주제입니다.

프로젝트는 이전에 만들어 둔 것에 이어서 시작해보겠습니다. 일단 코드로 페이지를 작성했던 MonkeyPage.cs를 삭제하고 "Forms Xaml Page" 항목으로 새롭게 MonkeyPage.cs를 추가합니다.

xamarin_forms_part2_1.png

그럼, WPF와 마찬가지로 MonkeyPage.xaml과 MonkeyPage.xaml.cs 파일이 생성됩니다. (하지만, 아쉽게도 XAML과 유사할 뿐 마이크로소프트가 지원하는 XAML과 동일하지는 않기 때문에 디자이너 화면은 제공되지 않습니다.)

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Part1.MonkeyPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Part1
{
    public partial class MonkeyPage
    {
        public MonkeyPage()
        {
            InitializeComponent();
        }
    }
}

그래도 보시는 바와 같이 WPF처럼 Data Binding 구문도 지원되고 속성도 거의 유사하게 제공하고 있기 때문에 편안하게 느껴집니다. ^^ 이제 지난번에 코드로 구성했던 UI를 XAML로 넣어줍니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Part1.MonkeyPage">
    <ListView x:Name="list" ItemsSource="{Binding Monkeys}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding Name}"
                    Detail="{Binding Location}">
                </TextCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

UI요소를 xaml 파일이 가져갔으므로 MonkeyPage.xaml.cs의 코드는 한결 더 가벼워집니다.

using Monkeys.ViewModels;

namespace Part1
{
    public partial class MonkeyPage
    {
        public MonkeyPage()
        {
            InitializeComponent();

            this.BindingContext = new MonkeysViewModel();
        }
    }
}

여기까지 변경하고 윈도우 폰 에뮬레이터로 실행하면, "지난번 글에서 코드로 구성한 예제"와 정확히 같은 실행 화면을 보여줍니다.

xamarin_forms_part1_3.png




ListView의 항목을 클릭한 것에 대한 상세 보기 페이지로 이동하는 기능도 추가해 볼까요? ^^ 이를 위해 기존 실습으로 작성된 DetailPage.cs 파일을 삭제하고 역시 이번에도 "Forms Xaml Page" 항목으로 새롭게 DetailPage.cs 파일을 다시 추가해줍니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Part1.DetailPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Part1
{
    public partial class DetailPage
    {
        public DetailPage()
        {
            InitializeComponent();
        }
    }
}

XAML에 기본 생성된 <Label /> 태그를 삭제하고 이전에 코드로 작성했던 상세 보기 페이지의 ScrollView/Label를 각각 추가합니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Part1.DetailPage" Title="{Binding Name}">
    <ScrollView Padding="20">
        <Label Text="{Binding Details}" />
    </ScrollView>
</ContentPage>

마찬가지로 DetailPage.xaml.cs 코드 역시 BindingContext만 지정하는 것으로 끝납니다.

namespace Part1
{
    public partial class DetailPage
    {
        public DetailPage(Monkey monkey)
        {
            InitializeComponent();
            this.BindingContext = monkey;
        }
    }
}

DetailPage XAML이 완성되었으니, 이제 MonkeyPage XAML에서 ListView 항목이 선택된 경우 이벤트를 처리하기 위해 XAML에 ItemTapped 이벤트를 추가합니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Part1.MonkeyPage">
    <ListView x:Name="list" ItemsSource="{Binding Monkeys}"
               ItemTapped="OnItemSelected">
        ...[생략]...
    </ListView>
</ContentPage>

그리고 MonkeyPage.xaml.cs 파일에 그에 대응되는 코드를 만들어 줍니다.

public void OnItemSelected(object sender, ItemTappedEventArgs args)
{
    var monkey = args.Item as Monkey;
    if (monkey == null)
        return;

    Navigation.PushAsync(new DetailPage(monkey));
    list.SelectedItem = null;
} 

실행하면, 역시 모든 동작은 "지난번 글에서 코드로 구성한 예제"와 동일합니다.

어떠세요? WPF의 경험을 살릴 수 있는 Xamarin.Forms! 마음에 드시나요? ^^ 사실 갈 길이 멉니다. XAML에 대한 디자이너 화면도 없고, 인텔리센스도 제공되지 않습니다. (Xamarin Studio에서는 xaml 페이지에 인텔리센스가 제공됩니다.) 게다가 간단한 UI 화면임에도 불구하고 윈도우 폰과 안드로이드 폰에서 다르게 나오기 때문에 이런 부분을 맞춰주어야 하는 상황이 오면 피곤할 수도 있습니다.

따라서, 원본의 "Learning Xamarin: Forms and XAML" 글에서도 나오지만, 아직은 LOB 성격의 앱으로 적당할 것 같습니다. 그 외의 앱을 제작한다면, 미리 신중하게 기술검토를 하시는 것이 좋을 것 같습니다. ^^

(첨부된 파일은 이번 글의 실습을 반영한 프로젝트입니다.)





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/27/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13438정성태11/9/20232664닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232839닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233092닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232994닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232772스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232470스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232548오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232917스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232754닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233034닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233130닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233313닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233469스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233247닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233223스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233375닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233460닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235748스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233284스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233991닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233519닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233799닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233571디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233767닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237067닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...