locked
How to Binding a combo box to an enum with Silverlight 3? RRS feed

  • 问题

  • C#代码 

    internal static class EnumValueCache
        {
            private static readonly IDictionary<Type, object[]> Cache = new Dictionary<Type, object[]>();
                   
            public static object[] GetValues(Type type)
            {
                if (!type.IsEnum)

                    throw new ArgumentException("Type '" + type.Name + "' is not an enum");

                object[] values;

                if (!Cache.TryGetValue(type, out values))
                {
                    values = type.GetFields()

                        .Where(f => f.IsLiteral)

                        .Select(f => f.GetValue(null)).ToArray();

                    Cache[type] = values;
                }
                return values;
            }
        }
       
        /// <summary> 
        /// Enum => EnumValues 
        /// </summary>
        public class EnumValuesConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null)
                    return null;

                else
                    return EnumValueCache.GetValues(value.GetType());
            }
           
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }

        public enum MyEnum
        {
            test1=0,
            test2,
            test3,
            test4,
            test5
        }

    XAML代码:

    <UserControl x:Class="Comboboxtest.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Comboboxtest"
        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
        <UserControl.Resources>
            <local:EnumValuesConverter x:Name="enumConverter"/>
            </UserControl.Resources>
      <Grid x:Name="LayoutRoot">
       <ComboBox Margin="126,190,220,0" VerticalAlignment="Top" Height="25" Name="comboxTest" ItemsSource="{Binding MyEnum, Mode=OneTime, Converter={StaticResource enumConverter}}"
                    SelectedItem="{Binding MyEnum, Mode=TwoWay}"/>
        </Grid>
    </UserControl>

    执行完后,combobox里面还是没有内容?哪里出错了呢?请高手帮助。

    谢谢先!

     

    2010年4月14日 7:43

答案

全部回复