첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형

TestProject.zip
0.01MB

▶ EnumerationTypeConverter.cs

using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;

namespace TestProject
{
    /// <summary>
    /// 열거형 타입 변환자
    /// </summary>
    public class EnumerationTypeConverter : EnumConverter
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - EnumerationTypeConverter(enumerationType)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="enumerationType">열거형 타입</param>
        public EnumerationTypeConverter(Type enumerationType) : base(enumerationType)
        {
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 변환하기 - ConvertTo(context, cultureInfo, value, targetType)

        /// <summary>
        /// 변환하기
        /// </summary>
        /// <param name="context">타입 설명자 컨텍스트</param>
        /// <param name="cultureInfo">문화 정보</param>
        /// <param name="value">값</param>
        /// <param name="targetType">타겟 타입</param>
        /// <returns>설명</returns>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cultureInfo, object value, Type targetType)
        {
            if(targetType == typeof(string) && value != null)
            {
                Type enumerationType = value.GetType();

                if(enumerationType.IsEnum)
                {
                    return GetDescription(value);
                }
            }

            return base.ConvertTo(context, cultureInfo, value, targetType);
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 설명 구하기 - GetDescription(value)

        /// <summary>
        /// 설명 구하기
        /// </summary>
        /// <param name="value">값</param>
        /// <returns>설명</returns>
        private object GetDescription(object value)
        {
            DescriptionAttribute attribute = EnumType.GetField(value.ToString())
                                                     .GetCustomAttributes(typeof(DescriptionAttribute), false)
                                                     .FirstOrDefault() as DescriptionAttribute;

            if(attribute != null)
            {
                return attribute.Description;
            }

            return Enum.GetName(EnumType, value);
        }

        #endregion
    }
}

 

728x90

 

▶ Country.cs

using System.ComponentModel;

namespace TestProject
{
    /// <summary>
    /// 국가
    /// </summary>
    [TypeConverter(typeof(EnumerationTypeConverter))]
    public enum Country : int
    {
        /// <summary>
        /// 호주
        /// </summary>
        [Description("호주 (AUS)")]
        AUS = 0,

        /// <summary>
        /// 미국
        /// </summary>
        [Description("미국 (USA)")]
        USA = 1,

        /// <summary>
        /// 영국
        /// </summary>
        [Description("영국 (GBR)")]
        GBR = 2,

        /// <summary>
        /// 프랑스
        /// </summary>
        [Description("프랑스 (FRA)")]
        FRA = 3,

        /// <summary>
        /// 독일
        /// </summary>
        [Description("독일 (GER)")]
        GER = 4,

        /// <summary>
        /// 스페인
        /// </summary>
        [Description("스페인 (ESP)")]
        ESP = 5,

        /// <summary>
        /// 자메이카
        /// </summary>
        [Description("자메이카 (JAM)")]
        JAM = 6,

        /// <summary>
        /// 한국
        /// </summary>
        [Description("한국 (KOR)")]
        KOR = 7,

        /// <summary>
        /// 우루과이
        /// </summary>
        [Description("우루과이 (URU)")]
        URU = 8
    }
}

 

300x250

 

▶ EnumerationHelper.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace TestProject
{
    /// <summary>
    /// 열거형 헬퍼
    /// </summary>
    public class EnumerationHelper
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 값으로 정렬하기 - SortByValue<TItem>(sourceList)

        /// <summary>
        /// 값으로 정렬하기
        /// </summary>
        /// <typeparam name="TItem">항목 타입</typeparam>
        /// <param name="sourceList">소스 리스트</param>
        /// <returns>값 정렬 리스트</returns>
        public static List<TItem> SortByValue<TItem>(List<TItem> sourceList)
        {
            List<string> itemList   = new List<string>();
            List<TItem>  targetList = new List<TItem>();

            foreach(TItem source in sourceList)
            {
                itemList.Add(source.ToString());
            }

            itemList.Sort();

            foreach(string item in itemList)
            {
                targetList.Add((TItem)Enum.Parse(typeof(TItem), item));
            }

            return targetList;
        }

        #endregion
        #region 설명으로 정렬하기 - SortByDescription<TItem>(sourceList)

        /// <summary>
        /// 설명으로 정렬하기
        /// </summary>
        /// <typeparam name="TItem">항목 타입</typeparam>
        /// <param name="sourceList">소스 리스트</param>
        /// <returns>설명 정렬 리스트</returns>
        public static List<TItem> SortByDescription<TItem>(List<TItem> sourceList)
        {
            List<string> itemList   = new List<string>();
            List<TItem>  targetList = new List<TItem>();

            foreach(TItem source in sourceList)
            {
                itemList.Add(GetDescriptionFromValue<TItem>(source));
            }

            itemList.Sort();

            foreach(string item in itemList)
            {
                targetList.Add(GetValueFromDescription<TItem>(item));
            }

            return targetList;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Private

        #region 값에서 설명 구하기 - GetDescriptionFromValue<TItem>(value)

        /// <summary>
        /// 값에서 설명 구하기
        /// </summary>
        /// <typeparam name="TItem">항목 타입</typeparam>
        /// <param name="value">값</param>
        /// <returns>설명</returns>
        private static string GetDescriptionFromValue<TItem>(TItem value)
        {
            DescriptionAttribute attribute = value.GetType()
                                                  .GetField(value.ToString())
                                                  .GetCustomAttributes(typeof(DescriptionAttribute), false)
                                                  .SingleOrDefault() as DescriptionAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }

        #endregion
        #region 설명에서 값 구하기 - GetValueFromDescription<TItem>(description)

        /// <summary>
        /// 설명에서 값 구하기
        /// </summary>
        /// <typeparam name="TItem">항목 타입</typeparam>
        /// <param name="description">설명</param>
        /// <returns>값</returns>
        private static TItem GetValueFromDescription<TItem>(string description)
        {
            Type type = typeof(TItem);

            if(!type.IsEnum)
            {
                throw new ArgumentException();
            }

            FieldInfo[] fieldInfoArray = type.GetFields();

            var attributeInfo = fieldInfoArray.SelectMany
            (
                f => f.GetCustomAttributes(typeof(DescriptionAttribute), false),
                (f, a) => new { Field = f, Attribute = a }
            )
            .Where(a => ((DescriptionAttribute)a.Attribute).Description == description)
            .SingleOrDefault();

            return attributeInfo == null ? default(TItem) : (TItem)attributeInfo.Field.GetRawConstantValue();
        }

        #endregion
    }
}

 

반응형

 

▶ MainWindow.xaml

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="800"
    Height="600"
    Title="열거형 정렬하기"
    Background="#426aa1"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid>
        <StackPanel
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
            <Label HorizontalAlignment="Left">
                열거형 값으로 정렬 :
            </Label>
            <ComboBox
                Width="300"
                Height="25"
                IsEditable="False"
                ItemsSource="{Binding Path=DefaultCountryList}" />
            <Label
                HorizontalAlignment="Left"
                Margin="0 10 0 0">
                국가 코드로 정렬 :
            </Label>
            <ComboBox
                Width="300"
                Height="25"
                IsEditable="False"
                ItemsSource="{Binding Path=CountryListSortedByValue}" />
            <Label
                HorizontalAlignment="Left"
                Margin="0 10 0 0">
                국가명으로 정렬 :
            </Label>
            <ComboBox
                Width="300"
                Height="25"
                IsEditable="False"
                ItemsSource="{Binding Path=CountryListSortedByDescription}" />
        </StackPanel>
    </Grid>
</Window>

 

▶ MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 디폴트 국가 리스트 - DefaultCountryList

        /// <summary>
        /// 디폴트 국가 리스트
        /// </summary>
        public List<Country> DefaultCountryList { get; set; }

        #endregion
        #region 값으로 정렬 국가 리스트 - CountryListSortedByValue

        /// <summary>
        /// 값으로 정렬 국가 리스트
        /// </summary>
        public List<Country> CountryListSortedByValue { get; set; }

        #endregion
        #region 설명으로 정렬 국가 리스트 - CountryListSortedByDescription

        /// <summary>
        /// 설명으로 정렬 국가 리스트
        /// </summary>
        public List<Country> CountryListSortedByDescription { get; set; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            SetList();

            DataContext = this;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 리스트 설정하기 - SetList()

        /// <summary>
        /// 리스트 설정하기
        /// </summary>
        private void SetList()
        {
            List<Country> defaultCountryList = Enum.GetValues(typeof(Country)).Cast<Country>().ToList();

            DefaultCountryList = defaultCountryList;

            CountryListSortedByValue = EnumerationHelper.SortByValue(defaultCountryList);

            CountryListSortedByDescription = EnumerationHelper.SortByDescription<Country>(defaultCountryList);
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by 사용자 icodebroker

댓글을 달아 주세요