2009-12-18 3 views
1

현재 Windows Forms GUI에서 작업 중이며 문자열 값 목록을 DisplayMembers로 표시해야하는 콤보가 있습니다. 사용자 정의 열거 형 값 목록을 ValueMember로 사용하십시오. 현재 데이터베이스 액세스 함수에서 List>를 반환하고 있는데 이것을 콤보 상자에 바인딩하고 싶습니다. 나는 .DisplayMember .DataMember 및 "Value"에 "Key"를 할당하고 .DataSource 속성에 목록을 할당하려고 시도했습니다. 그것은 작동하지 않기 때문에 명확하게 유효한 접근법이 아닙니다.DataSource로 List <KeyValuePair <UserEnum, String >>이있는 Windows Forms 콤보 상자 사용 - C#

누군가 나에게 좋은 양식의 실제 접근 방식을 제공 할 수 있습니까?

감사

답변

4

내가 열거 유형과 속성에 콤보 상자를 바인딩 할 수있는 2 개의 확장 방법과 함께 내 자신의 클래스 EnumPair<>을 사용합니까.

이것이 도움이되는지 확인해보십시오. 직접 열거 형을 사용할 수 있습니다.

구현 한 후이처럼 사용

당신이 당신의 양식 "으로 comboBox", 열거 소위 "MyEnumType"과 BindingSource에의 인스턴스라는 콤보 상자를 가정
comboBox.BindToEnumValue<MyEnumType>(myBindingSourceInstance, "PropertyNameOfBindingSource"); 

. PropertyNameOfBindingSource는 BindingSource에 MyEnumType의 PropertyType이있는 목록이있는 유형의 Property의 이름이어야합니다. 배경 작업 구현이 확장 방법이 필요하지 않은, 아래에 발견, 난 그냥 코드의 거의 동일한 라인을 쓰기 싫어 ;-)

public static class ComboBoxExtensions 
{ 
    public static void BindToEnumValue<TEnum>(this ComboBox cbo, BindingSource bs, string propertyName) 
    { 
     cbo.DataSource = EnumPair<TEnum>.GetValuePairList(); 
     cbo.ValueMember = EnumPair<TEnum>.ValueMember; 
     cbo.DisplayMember = EnumPair<TEnum>.DisplayMember; 
     cbo.DataBindings.Add(new Binding("SelectedValue", bs, propertyName)); 
    } 

    public static void BindClear(this ComboBox cbo) 
    { 
     cbo.DataSource = null; 
     cbo.DataBindings.Clear(); 
    } 
} 

/// <summary> 
/// Represents a <see cref="EnumPair"/> consisting of an value 
/// of an enum T and a string represantion of the value. 
/// </summary> 
/// <remarks> 
/// With this generic class every <see cref="Enum"/> can be 
/// dynamically enhanced by additional values, such as an empty 
/// entry, which is usefull in beeing used with 
/// <see cref="ComboBox"/>es. 
/// </remarks> 
/// <typeparam name="T">The type of the <see cref="Enum"/> to represent.</typeparam> 
public partial class EnumPair<T> 
{ 
    #region Constants 

    public const string ValueMember = "EnumValue"; 
    public const string DisplayMember = "EnumStringValue"; 

    #endregion 

    #region Constructor 

    /// <summary> 
    /// Initializes a new instance of the <see cref="EnumPair"/> class. 
    /// </summary> 
    public EnumPair() 
    { 
     Type t = typeof(T); 
     if (!t.IsEnum) 
     { 
      throw new ArgumentException("Class EnumPair<T> can only be instantiated with Enum-Types!"); 
     } 
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="EnumPair"/> class. 
    /// </summary> 
    /// <param name="value">The value of the enum.</param> 
    /// <param name="stringValue">The <see cref="string"/> value of the enum.</param> 
    public EnumPair(T value, string stringValue) 
    { 
     Type t = typeof(T); 
     if (!t.IsEnum) 
     { 
      throw new ArgumentException("Class EnumPair<T> can only be instantiated with Enum-Types!"); 
     } 

     this.EnumValue = value; 
     this.EnumStringValue = stringValue; 
    } 

    #endregion 

    #region Properties 

    /// <summary> 
    /// Gets or sets the value part of the <see cref="EnumPair"/>. 
    /// </summary> 
    public T EnumValue { get; set; } 

    /// <summary> 
    /// Gets or sets the string value of the <see cref="EnumPair"/>. 
    /// </summary> 
    public string EnumStringValue { get; set; } 

    #endregion 

    #region Methods 

    /// <summary> 
    /// Returns a <see cref="string"/> that represents the current <see cref="EnumPair"/>. 
    /// </summary> 
    public override string ToString() 
    { 
     return this.EnumStringValue; 
    } 

    /// <summary> 
    /// Generates a <see cref="List<T>"/> of the values 
    /// of the <see cref="Enum"/> T. 
    /// </summary> 
    public static List<EnumPair<T>> GetValuePairList() 
    { 
     List<EnumPair<T>> list = new List<EnumPair<T>>(); 
     EnumPair<T> pair = new EnumPair<T>(); 

     foreach (var item in Enum.GetValues(typeof(T))) 
     { 
      pair = new EnumPair<T>(); 
      pair.EnumValue = (T)item; 
      pair.EnumStringValue = ((T)item).ToString(); 
      list.Add(pair); 
     } 

     return list; 
    } 

    /// <summary> 
    /// Implicit conversion from enum value to <see cref="EnumPair<>"/> from that enum. 
    /// </summary> 
    /// <param name="e">The enum value to convert to.</param> 
    /// <returns>A <see cref="EnumPair<>"/> to the enum value.</returns> 
    public static implicit operator EnumPair<T>(T e) 
    { 
     Type t = typeof(EnumPair<>).MakeGenericType(e.GetType()); 
     return new EnumPair<T>((T)e, ((T)e).ToString()); 
    } 

    #endregion 
} 
+0

좀 더 가까이서보고 몇 가지 시도해 봐야하지만이 일은 내가하려는 일을 성취한다고 생각합니다. 감사합니다. 실제로이 문제가 해결되면이 대답을 수락합니다. –

+0

좋아요, 그래서이 코드가 작동하는지 확신하지만 코드를 이해하는 데 다소 시간이 걸립니다. 훌륭한 코드이지만이 클래스를 사용하는 예제 코드 조각은 향후 독자에게 도움이 될 것입니다. 너도 그걸 줄 수 있니? –

+0

여기에 집에서 개발 환경이 없지만 다음 주에 더 많은 코드 샘플을 붙여 넣을 수 있습니다. 지금 당장 내 추가 힌트는 내가 줄 수있는 모든 것입니다. 좋은 주말 되세요. –

0

이 같은 시도 할 수 있습니다 :

ddTemplates.DataSource = 
    Enum.GetValues(typeof(EmailTemplateType)) 
    .Cast<EmailTemplateType>().ToList() 
    .Select(v => new KeyValuePair<int, string>((int)v, v.ToString())).ToList(); 
관련 문제