作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我经常需要处理用户界面中的列表,这些列表会转换为“ViewModel”中的枚举值。我知道我可以通过提供枚举项名称的 ObjectDataProvider
将 ListView.ItemSource
直接绑定(bind)到枚举,但这通常不是最佳的,因为列表的可视化表示item 应该不同于枚举项目名称。
此外,枚举中的项目有时需要在视觉列表表示中被忽略。
例如:
enum WhatIWantIsA {
NiceHouse,
FastCar,
Nothing // omitted in the view
}
应转换为包含项目的列表:
A nice house
A fast car
所以我的问题是:您如何处理具有预定义条目数并在 ViewModel
中转换为枚举的列表?
最佳答案
您可以在绑定(bind)上使用 IValueConverter
将枚举转换为可读形式:
public class MyEnumValueConverter : IValueConverter
{
public object Convert(object value, Type type, ...)
{
var enumVal = (WhatIWantIsA)value;
switch (enumVal)
{
case "NiceHouse": return "A nice house";
case "FastCar": return "A fast car";
default: return "Unknown Value"; //or throw exception
}
}
public object ConvertBack(object value, Type type, ...)
{
return value; //probably don't need to implement this
}
}
在你的绑定(bind)上使用它:
<Resources>
<local:MyEnumValueConverter x:Key="myEnumConverter"/>
</Resources>
<ListView ItemsSource="{Binding Converter={StaticResource myEnumConverter}}"/>
这样,您的 ViewModel 可以继续使用枚举,并且用户会看到不错的值(value)。
希望这有助于...
编辑:更新示例以使用问题中提供的 Enum :-)
关于c# - ListView 和枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646055/
我是一名优秀的程序员,十分优秀!