www.topcredu.co.kr
뷰모델의 INotifyPropertyChanged 인터페이스는 클라이언트(뷰의 컨트롤)에 속성값의 변경을 통지를 하기위해 사용하며 사용자가 버튼을 클릭했을때 변경된 값이 라벨 컨트롤에 반영된다.
XAML의 Entry 텍스트 박스를 위한 public 프로퍼티 Ename과 private 프로퍼티 _Message, Label을 위한 public 프로퍼티인 Message가 포함되어 있다.
public 프로퍼티인 Message의 값이 변경되면 OnPropertyChanged() 메소드를 호출하여 PropertyChanged 이벤트를 호출하여 값의 변경을 Message 프로퍼티에 바인딩 되어 있는 Label 컨트롤에 알린다.
(자마린강좌/자마린실습)자마린폼즈 MVVM HelloWorld_데이터바인딩, Command 이벤트에 속성 바인딩 하기
1. 작성자 : 이 종 철
탑크리에듀 교육센터(www.topcredu.co.kr)
자마린 크로스플랫폼 앱개발
Xamarin.Forms MVVM HelloWorld
데이터 바인딩, command 바인딩
실습
2. 4.6.4 Xamarin.Forms MVVM HelloWorld(Command Data Binding)
“App7” 이라는 이름으로 Xamarin.Forms Cross-Platform App 프로젝트를 생성하자.
비어있는 앱, Xamarin.Forms, PCL을 선택하자.
이식가능 프로젝트(App7)에서 추가 >> 폴더로 ViewModel 폴더를 생성하자.
3. [EmpViewModel.cs] ViewModel 클래스를 작성하자.
INotifyPropertyChanged 인터페이스는 클라이언트(뷰의 컨트롤)에 속성값의 변경을 통지를 하
기위해 사용하며 사용자가 버튼을 클릭했을때 변경된 값이 라벨 컨트롤에 반영된다.
XAML의 Entry 텍스트 박스를 위한 public 프로퍼티 Ename과 private 프로퍼티 _Message,
Label을 위한 public 프로퍼티인 Message가 포함되어 있다.
public 프로퍼티인 Message의 값이 변경되면 OnPropertyChanged() 메소드를 호출하여
PropertyChanged 이벤트를 호출하여 값의 변경을 Message 프로퍼티에 바인딩 되어 있는
Label 컨트롤에 알린다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Xamarin.Forms;
namespace App7.ViewModel
{
// INotifyPropertyChanged 인터페이스는 클라이언트(뷰의 컨트롤)에 속성값의 변경을
통지를 하기위해 사용, 사용자가 버튼을 클릭했을때 변경된 값이 라벨 컨트롤에 반영된다.
public class EmpViewModel : INotifyPropertyChanged
{
public string Ename { get; set; }
private string _Message { get; set; }
public string Message
{
get { return _Message; }
set
{
4. _Message = value;
OnPropertyChanged();
}
}
public Command Introduce
{
get
{
return new Command( () => { Message = "My name is " + Ename; });
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =
null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
View 역할을 하는 [MainPage.xaml]
Button의 Command 이벤트가 ViewModel의 Introduce(Command 타입)에 바인딩 되어 있음
을 알수 있는데 버튼을 클릭하면 ViewModel의 public Command Introduce가 프로퍼티의 get
이 호출된다.
ContentPage의 BindingContext로 ViewModel 네임스페이스의 EmpViewModel이 설정되어 있
고 Entry 및 Label에 EmpViewModel의 Ename, Message 속성이 바인딩 되어 있다.
<?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:viewModel="clr-namespace:App7.ViewModel;assembly=App7"
x:Class="App7.MainPage">
<ContentPage.BindingContext>
<viewModel:EmpViewModel/>
</ContentPage.BindingContext>
<StackLayout Orientation="Vertical" Margin="10" VerticalOptions="Center"
HorizontalOptions="CenterAndExpand">
<Entry x:Name="Ename" Text="{Binding Ename}" />
<Label x:Name="Message" Text="{Binding Message}" />
<Button Text="당신을 소개하세요." Command="{Binding Introduce}" />
</StackLayout>
</ContentPage>
실행화면