This commit is contained in:
sherlockforrest
2023-06-20 09:22:53 +08:00
commit bf2ed2e31f
621 changed files with 271599 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
public class EnumDescriptionConvert : Collection<String>, IValueConverter
{
private Type type;
private IDictionary<Object, Object> valueToNameMap;
private IDictionary<Object, Object> nameToValueMap;
public Type Type
{
get { return this.type; }
set
{
if (!value.IsEnum)
throw new ArgumentException("类型不是枚举类", "value");
this.type = value;
Initialize();
}
}
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
{
return this.valueToNameMap[value];
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
{
return this.nameToValueMap[value];
}
private void Initialize()
{
this.valueToNameMap = this.type
.GetFields(BindingFlags.Static | BindingFlags.Public)
.ToDictionary(fi => fi.GetValue(null), GetDescription);
this.nameToValueMap = this.valueToNameMap
.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
Clear();
foreach (String name in this.nameToValueMap.Keys)
Add(name);
}
private static Object GetDescription(FieldInfo fieldInfo)
{
var descriptionAttribute =
(DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;
}
}

View File

@@ -0,0 +1,13 @@
internal class Model//注意属性的可访问修饰符
{
public string Name { get; set; }
public myEnum myEnum { get; set; }
}
public enum myEnum
{
[Description("Foo Bar")]
FooBar,
[Description("Bar Foo")]
BarFoo
}

View File

@@ -0,0 +1,35 @@
<Window.Resources>
<!-- local代表实例化该类x:key表示实例化的名称type是该实例的属性 -->
<local:EnumDescriptionConvert x:Key="enumItems" Type="{x:Type local:myEnum}" />
</Window.Resources>
<Grid>
<DataGrid
x:Name="dg"
AutoGenerateColumns="False"
CanUserAddRows="False">
<DataGrid.Columns>
<!-- 绑定的是这个枚举类集合 -->
<!-- 通过Converter把Description的Attribute作为选择项 -->
<DataGridComboBoxColumn
Header="Combobox"
ItemsSource="{Binding Source={StaticResource enumItems}}"
SelectedValueBinding="{Binding myEnum, Converter={StaticResource enumItems}, Mode=TwoWay}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
private ObservableCollection<Model> source = new ObservableCollection<Model>();
public MainWindow()
{
Model item = new Model()
{
myEnum = myEnum.BarFoo,
Name = "X"
};
source.Add(item);
InitializeComponent();
dg.ItemsSource = source;
}