是否有可能数据绑定到一个枚举,并显示用户友好的价值观? [英] Is it possible to databind to a Enum, and show user-friendly values?
本文介绍了是否有可能数据绑定到一个枚举,并显示用户友好的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想告诉我的合同,这两个声明的状态如下:
I want to show the status of my contract, both of which are declared as follows:
public enum RentStatus
{
[Description("Preparation description")]
Preparation,
[Description("Active description")]
Active,
[Description("Rented to people")]
Rented
}
public class RentContract
{
public int RentContractId { get; set; }
public virtual Premise Premise { get; set; }
public double Price { get; set; }
public RentStatus Status { get; set; }
}
我现在的XAML这是错误的。
My current XAML that is wrong
<ComboBox x:Name="RentStatusComboBox"
ItemsSource="{Binding RentContract}"
Grid.Row="2"
Grid.Column="1"
HorizontalAlignment="Stretch"
SelectedItem="{Binding RentContract.Status}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description}" Padding="0" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我已经看到了使用转换器和方法几种解决方案,但我不认为这些是能够。所以,当我改变我的UI状态我的实体被更新,以允许绑定
I've seen several solutions that use Converters and methods, but I don't think those are able to allow for databinding so that my entity is updated when I change the status in my UI.
编辑:下面的这个优秀的博文解决了我的问题。
Following this excellent blogpost solved my issue.
推荐答案
您可以创建枚举一个extenstion方法和使用反射可以设置的说明。 。请参考下面的代码
You can create a extenstion method for the Enum and using reflection you can set the description. refer the below code.
<ComboBox Width="200" Height="25" ItemsSource="{Binding ComboSource}"
DisplayMemberPath="Value"
SelectedValuePath="Key"/>
public class MainViewModel
{
public List<KeyValuePair<RentStatus, string>> ComboSource { get; set; }
public MainViewModel()
{
ComboSource = new List<KeyValuePair<RentStatus, string>>();
RentStatus re=RentStatus.Active;
ComboSource = re.GetValuesForComboBox<RentStatus>();
}
}
public enum RentStatus
{
[Description("Preparation description")]
Preparation,
[Description("Active description")]
Active,
[Description("Rented to people")]
Rented
}
public static class ExtensionMethods
{
public static List<KeyValuePair<T, string>> GetValuesForComboBox<T>(this Enum theEnum)
{
List<KeyValuePair<T, string>> _comboBoxItemSource = null;
if (_comboBoxItemSource == null)
{
_comboBoxItemSource = new List<KeyValuePair<T, string>>();
foreach (T level in Enum.GetValues(typeof(T)))
{
string Description = string.Empty;
FieldInfo fieldInfo = level.GetType().GetField(level.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
Description = attributes.FirstOrDefault().Description;
}
KeyValuePair<T, string> TypeKeyValue = new KeyValuePair<T, string>(level, Description);
_comboBoxItemSource.Add(TypeKeyValue);
}
}
return _comboBoxItemSource;
}
}
这篇关于是否有可能数据绑定到一个枚举,并显示用户友好的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文