Microsoft MVP성태의 닷넷 이야기
Phone: 11. Xamarin.Forms - 2. XAML을 이용한 페이지 개발 [링크 복사], [링크+제목 복사],
조회: 15836
글쓴 사람
정성태 (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)
13562정성태2/21/20241985오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242065닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242095디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242944오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242179닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241921Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241976Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242117닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241861VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241945닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241897닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242093닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242208Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242509개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242338개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242087개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241953Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241863닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241885오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241918Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241920오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241975VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242081Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242367개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242419닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242520닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...