2018년 1월 29일 월요일

[자마린폼즈 실습예제] Xamarin.Forms MVVM HelloWorld(Command Data Binding)

n  “App7” 이라는 이름으로 Xamarin.Forms Cross-Platform App 프로젝트를 생성하자.
8190bc7e133861fca87082230a72e6b9_1517216


n  비어있는 앱, Xamarin.Forms, PCL을 선택하자.
8190bc7e133861fca87082230a72e6b9_1517216
 

n  이식가능 프로젝트(App7)에서 추가 >> 폴더로 ViewModel 폴더를 생성하자.
8190bc7e133861fca87082230a72e6b9_1517216
 
n  [EmpViewModel.cs] ViewModel 클래스를 작성하자.
n  INotifyPropertyChanged 인터페이스는 클라이언트(뷰의 컨트롤)에 속성값의 변경을 통지를 하기위해 사용하며 사용자가 버튼을 클릭했을때 변경된 값이 라벨 컨트롤에 반영된다.
n  XAML의 Entry 텍스트 박스를 위한 public 프로퍼티 Ename과 private 프로퍼티 _Message, Label을 위한 public 프로퍼티인 Message가 포함되어 있다.
n  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 { getset; }
        private string _Message { getset; }
        public string Message
        {
            get { return _Message; }
            set
            {
                _Message = value;
                OnPropertyChanged();
            }
        }

        public Command Introduce
        {
            get
            {
                return new Command( () => { Message = "My name is " + Ename; });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberNamestring propertyName = null)
        {
            PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));
        }
    }
}

n  View 역할을 하는 [MainPage.xaml]
n  Button의 Command 이벤트가 ViewModel의 Introduce(Command 타입)에 바인딩 되어 있음을 알수 있는데 버튼을 클릭하면 ViewModel의 public Command Introduce가 프로퍼티의 get이 호출된다.
n  ContentPage의 BindingContext로 ViewModel 네임스페이스의 EmpViewModel이 설정되어 있고 Entry 및 Label에 EmpViewModel의 Ename, Message 속성이 바인딩 되어 있다.

<?xml version="1.0" encoding="utf-8" ?>
             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>

n  실행화면
 

댓글 없음:

댓글 쓰기