[XAMARIN] Resource Dictionary 사용하기

2019. 6. 2. 09:12IT/C#

Resouce Dictionary는 MS워드의 스타일과 비슷하나고 해야되나. 글자 크기, 색, 문자열 등 미리 정의해 놓고 그걸 가져다 쓰는것을 말한다. 예를 들어, A라고 치면 fontSize가 50이다 라고 정의 해놓고 <Label FontSize=A> 뭐 이런식으로 사용할 수 있다는 것이다. 동일한 스타일을 가진것들은 나중에 정의한 부분만 변경하면 동시에 모두가 바뀌므로 편리하게 사용할 수 있다.

보통 App.xaml에다가 정의해놓고 사용한다.

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ResourceDic.App">
    <Application.Resources>
        <x:Array x:Key="custGbn"
                Type="{x:Type x:String}">
            <x:String>General</x:String>
            <x:String>V.I.P</x:String>
            <x:String>V.V.I.P</x:String>
        </x:Array>
    </Application.Resources>
</Application>

그리고 사용하려는 페이지에서도 정의가 가능하다. App.xaml이 가장 상위 단계이고 contentPage, Label 등에서도 Resouce Dictionary를 정의할 수 있다. 가장 하위있는것이 적용된다. 즉 app.xaml에서 정의했다 하더라도 동일한것이 Label에도 정의되어 있으면 Label것이 적용된다. 가져다 쓸때 2가지 방법이 있는데 StaticResouce, DynamicResource가 있다. 전자는 한번 값이 설정되면 그 이후에는 절대 값이 바뀌지 않는것이고 후자는 처음 설정된 값이 이후에도 바뀔수 있다는것이다. 아래 예제에서는 그 차이를 알 수 있을것이다. 버튼을 누르면 DynamicResource로 정의된 부분만 글자 크기가 변하는것을 확인할 수 있다.

또, 글자크기 말고도 배열도 사용할 수 있는데 Array라는 클래스를 이용하여 배열을 사용한 예제가 아래와 같다.

값을 매칭 시킬때는 static인지 dynamic인지 결정하고 그것에 해당하는 KEY값을 입력해주면 가져올 수 있다.

<?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:ResourceDic" x:Class="ResourceDic.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <x:Double x:Key="fontSize">30</x:Double>
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout>
        <!-- Place new controls here -->
        <Picker Title="[고객등급을 선택하세요.]"
            ItemsSource="{StaticResource Key=custGbn}" />
        
        <Label Text="Xamarin.Forms!" FontSize="{StaticResource Key=fontSize}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"  />
        <Label Text="Xamarin.Forms!" FontSize="{DynamicResource Key=fontSize}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        
        <Button x:Name="BtnInc" StyleId="btnInc" Text="증가" Clicked="Handle_Clicked" />
        <Button x:Name="BtnDec" StyleId="btnDec" Text="감소" Clicked="Handle_Clicked" />
        
    </StackLayout>
</ContentPage>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ResourceDic;
using System.Diagnostics;

namespace ResourceDic
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(true)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        void Handle_Clicked(object sender, System.EventArgs e)
        {
            if ((sender as Button).StyleId == "btnInc")
            {
                this.Resources["fontSize"] = ((Double)this.Resources["fontSize"]) + 1;
            }
            else if ((sender as Button).StyleId == "btnDec")
            {
                this.Resources["fontSize"] = ((Double)this.Resources["fontSize"]) - 1;

            }
        }
    }
}

 

당장은 불편해 보이겠지만, 나중에 앱규모가 커지면 코딩수를 줄여줄수 있는 매우 편리한 도구가 될것으로 생각된다. 또한 디자이너들이 해놓을 디자인을 가져다 쓸때에도 저기에 정의가 되어 있어야 사용할 수 있으므로 잘 익혀두자.