자마린 크로스플랫폼 앱개발, Xamarin.Forms ListView 심플 데이터 바인딩, 컬렉션 바인딩 실습(Collection Binding)
- ListView 데이터 바인딩 기초 실습
- ListView에서 항목 클릭시 새 창 띄우면서
BindingContext를 이용하여 데이터 넘기기 실습
(Xamarin교육)자마린폼즈 리스트뷰 데이터바인딩, ListView Data Binding, BingContext 이용창띄우면서 데이터 전달 실습_구로디지털단지역 자마린교육센터/자마린학원/닷넷학원/C#학원/WPF학원
1. 작성자 : 이 종 철
탑크리에듀 교육센터(www.topcredu.co.kr)
자마린 크로스플랫폼 앱개발
Xamarin.Forms ListView 심플 데이
터 바인딩, 컬렉션 바인딩 실습
(Collection Binding)
- ListView 데이터 바인딩 기초 실습
- ListView에서 항목 클릭시 새 창 띄우면서
BindingContext를 이용하여 데이터 넘기기 실습
2. Xamarin.Forms의 ListView는 IEnumerable 형식의 ItemsSource 속성을 가지며 컬렉션의 항목
들을 표시한다. 이 항목은 모든 유형의 개체가 될 수 있는데 기본적으로 ListView는 각 항목
의 ToString() 메서드를 사용하여 해당 항목을 표시하도록 설계 되어 있다.
ListView 컬렉션의 항목(Item)은 셀(Cell)에서 파생되는 클래스가 포함 된 템플릿을 통해 원하
는 방식으로 표시 할 수 있는데 템플릿은 ListView의 모든 항목에 대해서 복제된다.
ViewCell 클래스를 사용하여 이러한 항목에 대한 사용자 정의 셀을 생성할 때 C# 코드에서는
다소 복잡하지만 XAML에서는 매우 간단하다.
예제 프로젝트에는 Emp라는 클래스가 있고 int 타입의 사번(Empno), string 타입의 이름
(Ename) 속성을 가진다. 또한 Emp 클래스에는 여러 사원을 컬렉션 형태로 담을 수 있는
Emps 속성을 가지며 static 생성자에서 Emps 속성을 초기화 했다.
static 속성인 Emp.Emps를 ListView의 ItemsSource로 설정하는 방법은 XAML에서는 x : Static
태그 확장을 사용하면 되고, C# 코드에서는 리스트뷰의 ItemSource 속성에 컬렉션을 할당하
면 된다.
XAML : <ListView ItemsSource="{x:Static local:Emp.Emps}" />
C#코드 : listView.ItemSource = Emp.Emps;
Xamarin.Forms, PCL(이식 가능한 클래스 라이브러리) 프로젝트를 생성하고 프로젝트명을
“App6”으로 입력하자.
[MainWindow.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"
xmlns:local="clr-namespace:App6"
x:Class="App6.MainPage">
<ListView ItemsSource="{x:Static local:Emp.Emps}" />
</ContentPage>
[Emp.cs]
3. using System;
using System.Collections.Generic;
namespace App6
{
public class Emp
{
public int Empno { get; set; }
public string Ename { get; set; }
public static IEnumerable<Emp> Emps { get; set; }
static Emp()
{
Emps = new List<Emp>
{
new Emp() { Empno = 1, Ename = "홍길동" },
new Emp() { Empno = 2, Ename = "박길동" },
new Emp() { Empno = 3, Ename = "정길동" },
new Emp() { Empno = 4, Ename = "나길동" },
new Emp() { Empno = 5, Ename = "김길동" }
};
}
public override string ToString()
{
return string.Format("Empno : {0}, Ename : {1}", Empno,
Ename);
}
}
}
[실행화면] : Emp 클래스의 ToString() 메소드가 실핼됨을 알 수 있다.
4. 이번에는 ListView의 항목(Item)에 대한 템플릿을 정의해서 데이터를 출력해 보자.
프로퍼티 엘리먼트로 ItemTemplate 속성을 분리하여 DataTemplate으로 설정 한 다음
ViewCell을 참조해야 하는데 ViewCell의 View 속성에 각 항목을 표시 할 하나 이상의 레이아
웃을 정의 할 수 있다.
아래 예문에서는 Grid 요소가 ViewCell의 View 프로퍼티 안에 정의되고 그 안에 Label 요소
를 들어하고 데이터 바인딩을 통해 Emp의 Empno, Ename 속성값들이 출력된다.
[MainWindow.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"
xmlns:local="clr-namespace:App6"
x:Class="App6.MainPage">
<ListView ItemsSource="{x:Static local:Emp.Emps}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding
5. Empno}" HorizontalOptions="Center"/>
<Label Grid.Column="1" Text="{Binding
Ename}" HorizontalOptions="Center"/>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
[실행결과]
이번에는 ListView에서 사용자가 항목을 클릭했을 때 새창을 띄우고 사번과 이름을 새로운
화면에 출력해 보자.
새창을 띄우기 위해서는 Navigation.PushAsync()를 사용해야 하는데 App.xaml.cs의 생성자 부
분을 아래와 같이 수정하자.
[App.xaml.cs]
public App()
{
6. InitializeComponent();
//MainPage = new App6.MainPage();
//PushAsync is not supported globally on Android, please use
a NavigationPage 오류 발생을 방지하기 위해 NavigationPage를 사용
MainPage = new NavigationPage(new MainPage());
}
[MainWindow.xaml]에서는 ListView를 코드 비하인드에서 사용해야 하므로 ListView에 이름
속성(x:Name)이 추가되었다.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App6"
x:Class="App6.MainPage">
<ListView x:Name="listView" ItemsSource="{x:Static local:Emp.Emps}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding
Empno}" HorizontalOptions="Center"/>
<Label Grid.Column="1" Text="{Binding
Ename}" HorizontalOptions="Center"/>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
[MainWindow.xaml.cs] 파일에서는 ListView의 ItemSelected 이벤트 처리용 코드가 추가되었
다.
7. using Xamarin.Forms;
namespace App6
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
listView.ItemSelected += async (sender, e) => {
if (e.SelectedItem == null) return;
var emp = e.SelectedItem as Emp;
//await DisplayAlert("Tapped!", e.SelectedItem + " was
tapped.", "OK");
var nextPage =new NextPage();
nextPage.BindingContext = emp;
await Navigation.PushAsync(nextPage);
};
}
}
}
추가 >> 새항목추강[서 Xamarin.Forms ContentPage 템플릿 형식으로 “NextPage.xaml”을
추가하자.
[NextPage.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="App6.NextPage">
<ContentPage.Content>
<StackLayout>
<Label Text="{Binding Empno}" />
<Label Text="{Binding Ename}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
[NextPage.xaml.cs] 파일은 수정할 필요 없다.
[Emp.cs] 파일은 이전과 동일하다.
8. using System;
using System.Collections.Generic;
namespace App6
{
public class Emp
{
public int Empno { get; set; }
public string Ename { get; set; }
public static IEnumerable<Emp> Emps { get; set; }
static Emp()
{
Emps = new List<Emp>
{
new Emp() { Empno = 1, Ename = "홍길동" },
new Emp() { Empno = 2, Ename = "박길동" },
new Emp() { Empno = 3, Ename = "정길동" },
new Emp() { Empno = 4, Ename = "나길동" },
new Emp() { Empno = 5, Ename = "김길동" }
};
}
public override string ToString()
{
return string.Format("Empno : {0}, Ename : {1}", Empno,
Ename);
}
}
}
[실행결과]