如何从枚举中绑定dropdownlist

时间:2014-01-05 13:53:13

标签: drop-down-menu enums

我有一个枚举

public enum LookupTypes
{
    [StringValue("UNIV")]
    University,
    [StringValue("COUR")]
    Course}

如何在下拉列表中将此值与UNIV绑定为值,将大学设置为文本

C#/ WPF

1 个答案:

答案 0 :(得分:0)

您需要一些转换器:

  • 要显示枚举列表("大学","课程"),您需要EnumValuesConverter,它包装" enumType .getValues()"
  • 然后,您可以使用提供的扩展程序方法StringValue()来获取属性的值。
  • 或使用执行相同操作的转化器EnumToStringValueConverter,以在UI上显示值(请参阅Label s)
  • 如果使用UNIV作为值"你的意思是,combo.SelectedValue是字符串UNIV运气不好,因为SelectedValuePath不处理函数,只处理属性。

试试这个野兽:

<Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:app="clr-namespace:WpfApplication1"
            Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <app:EnumValuesConverter x:Key="enumValuesConverter" />
        <app:EnumToStringValueConverter x:Key="enumToStringValueConverter" />
    </Window.Resources>
    <StackPanel x:Name="context">
        <ComboBox x:Name="combo"
                      ItemsSource="{Binding Source={x:Type app:LookupTypes}, Mode=OneTime, Converter={StaticResource enumValuesConverter}}"
                      SelectedItem="{Binding EnumProp, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding}" ToolTip="{Binding Converter={StaticResource enumToStringValueConverter}}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <Label Content="{Binding EnumProp}" ContentStringFormat="Selected Enum: {0}" />
        <Label Content="{Binding EnumProp, Converter={StaticResource enumToStringValueConverter}}" ContentStringFormat="Selected StringValue: {0}" />
        <Button Click="Button_Click" Content="Alert enum" />
    </StackPanel>
</Window>

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            context.DataContext = new MyViewModel {
                EnumProp = LookupTypes.Course
            };
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            LookupTypes type = (LookupTypes)combo.SelectedItem;
            MessageBox.Show(string.Format("Are you sure you want to use {0} ({1}) as lookup type?", type, type.StringValue()));
        }
    }

    [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public sealed class StringValueAttribute : Attribute {
        public StringValueAttribute(string stringValue) {
            StringValue = stringValue;
        }
        public string StringValue { get; private set; }
    }

    public static class StringValueExtensions {
        public static string StringValue(this Enum This) {
            System.Reflection.FieldInfo fieldInfo = This.GetType().GetField(This.ToString());
            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
            return attribs.Length == 0 ? null : attribs[0].StringValue;
        }
    }

    public enum LookupTypes {
        [StringValue("UNIV")]
        University,
        [StringValue("COUR")]
        Course
    }

    class MyViewModel {
        public LookupTypes EnumProp { get; set; }
    }

    [ValueConversion(typeof(Enum), typeof(string[]))]
    public class EnumValuesConverter : IValueConverter {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (value == null) return Binding.DoNothing;
            return Enum.GetValues((Type)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
        #endregion
    }

    [ValueConversion(typeof(Enum), typeof(string))]
    public class EnumToStringValueConverter : DependencyObject, IValueConverter {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (value == null) return Binding.DoNothing;
            return ((Enum)value).StringValue();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
        #endregion
    }
}