WPF Localization (다국어)

C# 2014. 5. 7. 14:38

1. ResouceDictionary를 만든다. (리소스사전)


2. 다국어파일을 정의한다.

  네이밍은 ko-KR, en-US 등, C# 고유 로컬라이즈 이름을 붙혀주면 동적 할당 하기가 쉽다.


예)

Localization.en-US.xaml

Localization.ko-KR.xaml


3. ResourceDictionary 상세

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:system="clr-namespace:System;assembly=mscorlib"
                    >
    <system:String x:Key="Hello">안녕하세요~</system:String>
</ResourceDictionary>


현재 언어상태를 가져온다.

string currentLanguage = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();


언어설정을 셋팅한다.

System.Threading.Thread.CurrentThread.CurrentUICulture = new system.Globalization.CultureInfo(currentLanguage);



4. 다국어 파일 가져오기


List<ResourceDictionary> dicList = new List<ResourceDictionary>();
            foreach (ResourceDictionary dic in System.Windows.Application.Current.Resources.MergedDictionaries)
            {
                dicList.Add(dic);
            }
                        
            string currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();
            string requestedCulture = "Resources/" + string.Format("Localization.{0}.xaml", currentCulture);
            
            ResourceDictionary resourceDictionary = dicList.FirstOrDefault(d => d.Source.OriginalString == requestedCulture);
            if (resourceDictionary == null)
            {
                requestedCulture = "Localization.en-US.xaml";
                resourceDictionary = dicList.FirstOrDefault(d => d.Source.OriginalString == requestedCulture);
            }
            else
            {
                System.Windows.Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
                System.Windows.Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
            }


5. 실습


string hello = FindResource("Hello").ToString();


위 변수에 "안녕하세요" 라는 값이 대입 된다.


FindResource로 정의된 x:Key값을 넣어주면 언어에 맞게 값을 가져온다.


'C#' 카테고리의 다른 글

WPF UIElement 이미지로 저장하기  (0) 2014.02.27
Enum  (0) 2014.01.21
코딩규약  (0) 2014.01.21
Posted by 자바리즘
,