18
자마린 계산기 실습예제 (Xamarin.Forms, MVVM, XAML) http://www.topcredu.co.kr http://ojc.asia 탑크리에듀,오라클자바커뮤니티제공 Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기 구현(크로스 플랫폼)

탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

  • Upload
    3-2

  • View
    1.242

  • Download
    1

Embed Size (px)

Citation preview

Page 1: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

자마린 계산기 실습예제

(Xamarin.Forms, MVVM, XAML)

http://www.topcredu.co.kr

http://ojc.asia

탑크리에듀,오라클자바커뮤니티제공

Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기 구현(크로스 플랫폼)

Page 2: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

(본 예제는 developer.xamarin.com의 XAML 예제를 참조하여 만들었습니다.)

MVVM, XAML 패턴을 이해하기 위한 사칙연산만 수행하는 간단한 계산기를

만들어 보자. 본 예제를 기본으로 복잡한 계산기 기능을 완성해 보세요.

프로젝트 생성(Xamarin Cross-Platform, Blank Xaml App)

- iPhone App을 위해서 Mac 장비가 있어야 한다.

프로젝트명 : Calc

Portable, Android, iOS, Window UWP, Window8 App, Windows Phone8을 위한

6개의 프로젝트가 생성되며 프로젝트 생성 후 모습은 다음과 같다.

Page 3: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

Calc(이식가능) 프로젝트에 App.xaml 파일이 응용프로그램 시작점이며 그안에

서 MainPage를 호출하면서 프로그램이 시작된다. 계산기 예제의 경우

Calc(이식가능) 프로젝트 쪽에만 공통 코드를 작성하면 안드로이드, 아이폰,

윈도우등 크로스 플랫폼으로 배포가능 하다.

App.xaml.cs 파일은 수정할 필요는 없고 MainPage를 호출하는 부분은 아래와

같으니 확인만 하자.

public App()

{

InitializeComponent();

MainPage = new Calc.MainPage();

}

Page 4: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

Calc(이식가능) 프로젝트의 MainPage.xaml(UI담당, VIEW) 파일을 아래와 같이

만들자. MainPage.xaml.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"

xmlns:local="clr-namespace:Calc;assembly=Calc"

x:Class="Calc.MainPage"

Title="Calculator Page">

<Grid HorizontalOptions="Center"

VerticalOptions="Center">

<!-- BindingContext에 ViewModel 클래스의 이름을 기술 -->

<Grid.BindingContext>

<local:CalcViewModel />

</Grid.BindingContext>

<!-- Grid의 행과 열을 정의 -->

<Grid.RowDefinitions>

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto" />

<RowDefinition Height="Auto" />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

Page 5: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<!-- 최상단 행을 위한 내부 그리드 정의 -->

<Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto" />

</Grid.ColumnDefinitions>

<Frame Grid.Column="0">

<Label Text="Xamarin Calculator"

HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

IsVisible="true"

FontAttributes="Bold" TextColor="Black" />

</Frame>

</Grid>

<!-- 두번째 행을 위한 내부 그리드 정의, 출력텍스트박스, BACK버튼, Clear

버튼 -->

<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="4">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

<ColumnDefinition Width="Auto" />

<ColumnDefinition Width="Auto" />

</Grid.ColumnDefinitions>

<!-- ViewModel 클래스의 DisplayText 속성과 바인딩 -->

<Frame Grid.Column="0"

OutlineColor="Accent">

<Label Text="{Binding DisplayText}" />

</Frame>

Page 6: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

<!-- 버튼의 Command 이벤트에 Command명을 지정하고 바인딩-->

<!-- ViewModel 클래스에서 DeleteCharCommand 속성이 정의되야 하고

-->

<!-- 실제 버튼이 눌러졌을 때 Command에 대한 이벤트 핸들러를 정의해

야 한다.-->

<Button Text="BACK"

Command="{Binding DeleteCharCommand}"

Grid.Column="1"

BorderWidth="0" />

<Button Text="Clear"

Command="{Binding ClearCommand}"

Grid.Column="2"

BorderWidth="0" />

</Grid>

<Button Text="1"

Command="{Binding AddCharCommand}"

CommandParameter="1"

Grid.Row="2" Grid.Column="0" />

<Button Text="2"

Command="{Binding AddCharCommand}"

CommandParameter="2"

Grid.Row="2" Grid.Column="1" />

<Button Text="3"

Command="{Binding AddCharCommand}"

CommandParameter="3"

Grid.Row="2" Grid.Column="2" />

<Button Text="+"

Command="{Binding OperationCommand}"

Page 7: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

CommandParameter="+"

Grid.Row="2" Grid.Column="3" />

<Button Text="4"

Command="{Binding AddCharCommand}"

CommandParameter="4"

Grid.Row="3" Grid.Column="0" />

<Button Text="5"

Command="{Binding AddCharCommand}"

CommandParameter="5"

Grid.Row="3" Grid.Column="1" />

<Button Text="6"

Command="{Binding AddCharCommand}"

CommandParameter="6"

Grid.Row="3" Grid.Column="2" />

<Button Text="-"

Command="{Binding OperationCommand}"

CommandParameter="-"

Grid.Row="3" Grid.Column="3" />

<Button Text="7"

Command="{Binding AddCharCommand}"

CommandParameter="7"

Grid.Row="4" Grid.Column="0" />

<Button Text="8"

Command="{Binding AddCharCommand}"

CommandParameter="8"

Grid.Row="4" Grid.Column="1" />

Page 8: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

<Button Text="9"

Command="{Binding AddCharCommand}"

CommandParameter="9"

Grid.Row="4" Grid.Column="2" />

<Button Text="*"

Command="{Binding OperationCommand}"

CommandParameter="*"

Grid.Row="4" Grid.Column="3" />

<Button Text="0"

Command="{Binding AddCharCommand}"

CommandParameter="0"

Grid.Row="5" Grid.Column="0" />

<Button Text="."

Command="{Binding AddCharCommand}"

CommandParameter="."

Grid.Row="5" Grid.Column="1" />

<Button Text="="

Command="{Binding CalcCommand}"

CommandParameter="="

Grid.Row="5" Grid.Column="2" />

<Button Text="/"

Command="{Binding OperationCommand}"

CommandParameter="/"

Grid.Row="5" Grid.Column="3" />

</Grid>

</ContentPage>

Calc(이식가능) 프로젝트에 VIEW를 표현하고 Command를 구현한 ViewModel

을 만들자. (CalcViewModel.cs)

Page 9: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

using System;

using System.ComponentModel;

using System.Windows.Input;

using Xamarin.Forms;

namespace Calc

{

class CalcViewModel : INotifyPropertyChanged

{

//아래 두 필드는 속성으로 구현되어 있다.

//출력될 문자들을 담아둘 변수

string inputString = "";

//계산기화면의 출력 텍스트박스에 대응되는 필드

string displayText = "";

//속성이 바뀔때 이벤트 발생하도록 이벤트 정의

public event PropertyChangedEventHandler PropertyChanged;

//생성자

public CalcViewModel()

{

//이벤트 핸들러 정의

//숫자 버튼을 클릭할 때 실행

this.AddCharCommand = new Command<string>((key) =>

{

this.InputString += key;

});

//백스페이스 버튼을 클릭할 때 실행, 한글자 삭제

Page 10: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

this.DeleteCharCommand = new Command((nothing) =>

{

this.InputString = this.InputString.Substring(0,

this.InputString.Length - 1);

},

(nothing) =>

{

// Return true if there's something to delete.

return this.InputString.Length > 0;

});

//Clear 버튼을 클릭할 때 실행, 출력창을 전부 지운다.

this.ClearCommand = new Command((nothing) =>

{

// Clear

this.InputString = "";

});

//+,-,*,/ 버튼을 클릭할 때 실행

//현재출력창의 숫자를 Op1 속성에 저장, Op속성에 클릭한 연산

자 저장

//계산기의 출력화면을 Clear

this.OperationCommand = new Command<string>((key) =>

{

this.Op = key;

this.Op1 = Convert.ToDouble(this.InputString);

this.InputString = "";

});

// =버튼을 클릭시 실행

this.CalcCommand = new Command<string>((nothing) =>

{

Page 11: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

this.Op2 = Convert.ToDouble(this.InputString);

switch (this.Op)

{

case "+": this.InputString = (this.Op1 +

this.Op2).ToString(); break;

case "-": this.InputString = (this.Op1 - this.Op2).ToString();

break;

case "*": this.InputString = (this.Op1 * this.Op2).ToString();

break;

case "/": this.InputString = (this.Op1 / this.Op2).ToString();

break;

}

});

}

// Public 속성들을 정의

public string InputString

{

protected set

{

if (inputString != value)

{

inputString = value;

OnPropertyChanged("InputString");

this.DisplayText = inputString;

// 숫자버튼을 클릭하면 백스페이스 버튼을 활성화 시킨

다.

((Command)this.DeleteCharCommand).ChangeCanExecute();

}

Page 12: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

}

get { return inputString; }

}

//계산기의 출력창과 바인딩된 속성

public string DisplayText

{

protected set

{

if (displayText != value)

{

displayText = value;

OnPropertyChanged("DisplayText");

}

}

get { return displayText; }

}

public string Op { get; set; }

public double Op1 { get; set; }

public double Op2 { get; set; }

// 숫자 클릭

public ICommand AddCharCommand { protected set; get; }

// <- 클릭, 한글자씩 삭제

public ICommand DeleteCharCommand { protected set; get; }

// C 클릭시 DisplayText 전체를 지운다.

public ICommand ClearCommand { protected set; get; }

Page 13: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

// +, -, *, / 클릭

public ICommand OperationCommand { protected set; get; }

// = 클릭

public ICommand CalcCommand { protected set; get; }

protected void OnPropertyChanged(string propertyName)

{

//이벤트를 발생시킨다.

if (PropertyChanged != null)

PropertyChanged(this, new

PropertyChangedEventArgs(propertyName));

}

}

}

Calc.Droid 프로젝트에서 우측 마우스 클릭 후 시작프로젝트로 설정 후 안드

로이드폰을 연결하거나 에뮬레이터로 실행화면 된다.

안드로이드 폰에서의 실행화면

Page 14: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

안드로이드 에뮬레이터에서의 실행화면

Page 15: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)
Page 16: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)

Calc.iOS 프로젝트에서 우측 마우스 버튼 믈릭 후 시작프로젝트로 설정 후 아

이폰 시뮬레이터로 실행하면 된다.

아이폰 시뮬레이터에서의 실행화면

Page 17: 탑크리에듀,자마린(Xamarin)기초교육강좌(Xamarin.Forms, MVVM, XAML을 이용한 간단한 계산기)