ListView 기본 (2)

ListView에 데이터를 바인딩 하는 과정은 크게 두가지가 있다.

  • 아이템 소스 설정 - 간단한 리스트 또는 배열을 이용
  • 데이터 바인딩 - ListView와 모델간의 관계를 설정. 여기에서 MVVM패턴을 다룬다.

아이템 소스

ListView 는 ItemSource 속성을 사용해 데이터를 생성할 수 있다. 이 속성은 IEnumerable을 구현하는 어떤 컬렉션이든 수용할 수 있다. ListView를 생성하는 가장 간단한 방법은 문자열 배열을 이용하는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var listView = new ListView();
listView.ItemsSource = new string[]{
"mono",
"monodroid",
"monotouch",
"monorail",
"monodevelop",
"monotone",
"monopoly",
"monomodal",
"mononucleosis"
};
//monochrome will not appear in the list because it was added
//after the list was populated.
listView.ItemsSource.Add("monochrome");

ListView with string array

기본적으로, ListView는 ToString을 호출하고 그 결과를 TextCell에 표현한다. 셀의 커스터마이징에 관해서는 Cell Appearance를 참고하라.
하지만, 이 방법은 기반인 문자열 배열이 이미 ItemSource에 이미 보내졌기 때문에 변경사항이 반영되지 않는다. 만일, ListView에 이러한 변경이나 추가, 삭제가 자동으로 업데이트 되길 원한다면 ObservableCollection을 사용해야 한다. 이것은 System.Collections.ObjectModel에 정의되어 있다. 이것은 List와 비슷하지만, 컬렉션의 변화를 ListView에 알려줄 수 있다.

1
2
3
4
5
ObservableCollection<Employees> employeeList = new ObservableCollection<Employess>();
listView.ItemsSource = employeeList;
//Mr. Mono will be added to the ListView because it uses an ObservableCollection
employeeList.Add(new Employee(){ DisplayName="Mr. Mono"});

데이터 바인딩

데이터 바인등은 사용자 인터페이스의 속성과 ViewModel과 같은 CLR객체의 속성을 연결하는 과정을 말한다. 데이터 바인딩 덕분에 사용자 인터페이스를 갱신하는 많은 귀챦은 작업들이 간편해 질수 있다. 데이터 바인딩의 기초에 관한 글을 참고하라.

바인딩 셀

셀의 속성은 ItemSource에 객체의 속성과 바인딩 될 수 있다. 아래 예제는 ListView에 직원들의 목록을 표시하는 예제이다.

직원 클래스:

1
2
3
public class Employee{
public string DisplayName {get; set;}
}

ListView의 ItemsSource에 ObservableCollection 를 설정한다.

1
2
3
4
5
6
7
ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public EmployeeListPage()
{
//defined in XAML to follow
EmployeeView.ItemsSource = employees;
...
}

다음과 같이 샘플 데이터를 생성한다.

1
2
3
4
5
6
7
8
9
10
public EmployeeListPage()
{
...
employees.Add(new Employee{ DisplayName="Rob Finnerty"});
employees.Add(new Employee{ DisplayName="Bill Wrestler"});
employees.Add(new Employee{ DisplayName="Dr. Geri-Beth Hooper"});
employees.Add(new Employee{ DisplayName="Dr. Keith Joyce-Purdy"});
employees.Add(new Employee{ DisplayName="Sheri Spruce"});
employees.Add(new Employee{ DisplayName="Burt Indybrick"});
}

다음은 ListView를 바인딩하는 XAML 이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:constants="clr-namespace:XamarinFormsSample;assembly=XamarinFormsXamlSample"
x:Class="XamarinFormsXamlSample.Views.EmployeeListPage"
Title="Employee List">
<ListView x:Name="EmployeeView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>

각 행의 레이아웃은 ListView.ItemTemplate 요소이며, TextCell에 이름이 바인딩되어 있다. 결과는 아래와 같다.
Result

선택된 요소의 바인딩

ListView의 현재 선택된 아이템을 바인드 하고 싶을 경우 이벤트 핸들러를 사용해 변화에 대응하는것 보다, XAML의 SelectedItem속성을 사용할 수 있다.

1
2
3
4
5
<ListView x:Name="listView"
SelectedItem="{Binding Source={x:Reference SomeLabel},
Path=Text}">
</ListView>

ListView의 ItemsSource는 문자열 배열이며, SomeLabel의 Text속성이 SelectedItem에 바인딩될 것이다.