コード例 #1
0
        /// <summary>
        /// Sets the datasource for enumerations.
        /// </summary>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <param name="this">This ComboBox.</param>
        /// <param name="insertNull">Insert null-object (use as non-selected).</param>
        /// <param name="ignoreValues">Values not to be used.</param>
        public static void DataSource <TEnum>(this ComboBox @this, bool insertNull = false, TEnum[] ignoreValues = null) where TEnum : struct
        {
            Contract.Requires(typeof(TEnum).IsEnum);

            @this.DataSource(
                (insertNull ? new[] { new Tuple <object, string>(null, null) } : new Tuple <object, string> [0])
                .Concat(Enum.GetValues(typeof(TEnum)).Cast <object>()
                        .Where(i => ignoreValues == null || ignoreValues.Length == 0 || !ignoreValues.Contains((TEnum)i))
                        .Select(
                            i => {
                var fieldInfo = typeof(TEnum).GetField(i.ToString());
                Contract.Assert(fieldInfo != null, "Can not find field");
                var attribute =
                    (DisplayNameAttribute)fieldInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault();
                return(Tuple.Create(i, attribute?.DisplayName ?? i.ToString()));
            })).ToArray(), nameof(Tuple <object, string> .Item2), nameof(Tuple <object, string> .Item1)
                );
        }