我想显示我的合同的状态,两者声明如下:
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 是错误的
<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 中的状态时更新我的实体。
编辑:正在关注这篇优秀的博文解决了我的问题。
您可以为枚举创建扩展方法,并使用反射来设置描述。参考下面的代码。
<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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)