2010-10-21 7 views

Respuesta

79

Sí, es posible. Esto lo hará. Digamos que tenemos la enumeración

public enum MyEnum 
{ 
    [Description("MyEnum1 Description")] 
    MyEnum1, 
    [Description("MyEnum2 Description")] 
    MyEnum2, 
    [Description("MyEnum3 Description")] 
    MyEnum3 
} 

Entonces podemos usar el ObjectDataProvider como

xmlns:MyEnumerations="clr-namespace:MyEnumerations" 
<ObjectDataProvider MethodName="GetValues" 
       ObjectType="{x:Type sys:Enum}" 
       x:Key="MyEnumValues"> 
    <ObjectDataProvider.MethodParameters> 
     <x:Type TypeName="MyEnumerations:MyEnum" /> 
    </ObjectDataProvider.MethodParameters> 
</ObjectDataProvider> 

Y para el ListBox nos fijamos el ItemsSource a MyEnumValues ​​y aplicar un ItemTemplate con un convertidor.

<ListBox Name="c_myListBox" SelectedIndex="0" Margin="8" 
     ItemsSource="{Binding Source={StaticResource MyEnumValues}}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={StaticResource EnumDescriptionConverter}}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

Y en el convertidor obtenemos la descripción y devolverlo

public class EnumDescriptionConverter : IValueConverter 
{ 
    private string GetEnumDescription(Enum enumObj) 
    { 
     FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString()); 

     object[] attribArray = fieldInfo.GetCustomAttributes(false); 

     if (attribArray.Length == 0) 
     { 
      return enumObj.ToString(); 
     } 
     else 
     { 
      DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute; 
      return attrib.Description; 
     } 
    } 

    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     Enum myEnum = (Enum)value; 
     string description = GetEnumDescription(myEnum); 
     return description; 
    } 

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return string.Empty; 
    } 
} 

El método GetEnumDescription probablemente debería ir a otro lugar, pero usted consigue la idea :)

+0

Gracias, voy a intentarlo ahora :) –

+4

Me encanta, lo atrapé. Utilicé un pequeño linq para emparejar GetEnumDescription, puedes engancharlo aquí http://pastebin.com/XLm9hbhG – Will

+2

¿Entonces tienes que hacer un convertidor para cada tipo de enumeración? – Carlo

0

Se puede definir un archivo ressource en su proyecto (archivo * .resx). En este archivo se debe definir "key-value-pairs", algo como esto:

"YellowCars" : "Yellow Cars", 
"RedCars" : "Red Cars", 

y así sucesivamente ...

Las teclas son iguales a sus ENUM entradas, algo como esto:

public enum CarColors 
{ 
    YellowCars, 
    RedCars 
} 

y así sucesivamente ...

Cuando se utiliza WPF se puede implementar en su XAML-Code, algo como esto:

<ComboBox ItemsSource="{Binding Source={StaticResource CarColors}}" SelectedValue="{Binding CarColor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={StaticResource CarColorConverter}}" /> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

Entonces usted debe escribir su convertidor, algo como esto:

using System; 
using System.Globalization; 
using System.Resources; 
using System.Windows.Data; 

public class CarColorConverter : IValueConverter 
{ 
    private static ResourceManager CarColors = new ResourceManager(typeof(Properties.CarColors)); 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var key = ((Enum)value).ToString(); 
     var result = CarColors.GetString(key); 
     if (result == null) { 
      result = key; 
     } 

     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

Mi respuesta llega tarde a 7 años ;-) Pero tal vez puede ser utilizado por otra persona!

Cuestiones relacionadas