столбец сетки, представляющий значение, сохраненное на сервере sql в tinyint и перечисление в c#, не показывающее выбранный элемент в conbobox - PullRequest
0 голосов
/ 28 марта 2020

Я сохранил значение моего перечисления на сервере sql как tinyint. Я хочу показать эти значения и сделать их редактируемыми в gridview, по этой причине я использую комбинированный список. это мой enum класс. Я нашел этот код на линии. код работал нормально, когда в моей модели был ученик, но я исключил sql исключений, которые мне пришлось удалить.

namespace WpfApp1.Enum_
{
    public class EnumBindingSourceExtension : MarkupExtension
    {
        private Type _enumType;
        public Type EnumType
        {
            get { return this._enumType; }
            set
            {
                if (value != this._enumType)
                {
                    if (null != value)
                    {
                        Type enumType = Nullable.GetUnderlyingType(value) ?? value;
                        if (!enumType.IsEnum)
                            throw new ArgumentException("Type must be for an Enum.");
                    }

                    this._enumType = value;
                }
            }
        }

        public EnumBindingSourceExtension() { }

        public EnumBindingSourceExtension(Type enumType)
        {
            this.EnumType = enumType;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (null == this._enumType)
                throw new InvalidOperationException("The EnumType must be specified.");

            Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;

            Array enumValues = System.Enum.GetValues(actualEnumType);

            if (actualEnumType == this._enumType)
                return enumValues;

            Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
            enumValues.CopyTo(tempArray, 1);
            return tempArray;
        }
    }
    public class EnumDescriptionTypeConverter : EnumConverter
    {
        public EnumDescriptionTypeConverter(Type type)
            : base(type)
        {
        }
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                if (value != null)
                {
                    FieldInfo fi = value.GetType().GetField(value.ToString());
                    if (fi != null)
                    {
                        var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        return ((attributes.Length > 0) && (!String.IsNullOrEmpty(attributes[0].Description))) ? attributes[0].Description : value.ToString();
                    }
                }

                return string.Empty;
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
public enum MyType : byte
{
    Undeterment,
    Mixed,
    Non_Calcified,
    Calcified,
};

}

<DataGridTemplateColumn Header="Type">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox  Name="hi" ItemsSource="{Binding Source={loc:EnumBindingSource {x:Type loc:MyType}}}"   SelectedItem="{Binding RType, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
[Table("ReportDetail")]
public partial class ReportDetail {
 [Key]
        public int RDId { get; set; }

        public int? RId { get; set; }

        public byte? Segment { get; set; }

        public byte? RType { get; set; }

}

, но код не показывает выбранный элемент, который я прочитал из своей базы данных.

1 Ответ

0 голосов
/ 28 марта 2020

решение, которое я предложил, чтобы изменить результат запроса и конструктор вызова для моего класса и присвоить значения в выпадающем списке для значения enum в моем классе

  public ReportDetail(int rDId, int? rId, byte? segment, byte? rType, byte? stenosis, int? x, int? y, int? rLength = 0)
        {
            RDId = rDId;
            RId = rId;
            Segment = segment;
            RType = rType;
            Stenosis = stenosis;
            X = x;
            Y = y;
            RLength = rLength;
            Type =(MyType)rType;
        }
    <ComboBox  Name="hi" ItemsSource="{Binding Source={loc:EnumBindingSource {x:Type loc:MyType}}}"   SelectedItem="{Binding Type, UpdateSourceTrigger=PropertyChanged}"/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...