【问题标题】:ListView and enumsListView 和枚举
【发布时间】:2011-04-13 07:54:13
【问题描述】:

我经常需要处理用户界面中的列表,这些列表会转换为“ViewModel”中的枚举值。我知道我可以通过提供枚举项名称的ObjectDataProvider 直接将ListView.ItemSource 绑定到枚举,但这通常不是最佳的,因为列表项的视觉表示应该不同枚举项名称。

此外,枚举中的项目有时需要在可视列表表示中省略。

例如:

    enum WhatIWantIsA        {
        NiceHouse,
        FastCar,
        Nothing // omitted in the view
    }

应转换为包含项目的列表:

    A nice house
    A fast car

所以我的问题是:您如何处理具有预定义条目数量并转换为 ViewModel 中的枚举的列表?

【问题讨论】:

  • 这个答案可能会有所帮助:stackoverflow.com/questions/5350684/adding-enum-to-combobox/… 我个人会采用我建议的解决方案 - 这非常适合视图模型。
  • 抱歉,我不是这个意思。我编辑了我的问题以使其更清楚
  • 其实我认为是,关键是你需要定义项目列表并将它们与枚举值相关联。我在该答案中描述的类具有NameValue,名称是您定义的。或者,用属性装饰枚举并使用一些通用代码为您返回自定义类型。
  • 感谢亚当!对,这实际上是我的意思。您甚至可以使用该解决方案省略枚举项

标签: c# wpf mvvm viewmodel


【解决方案1】:

您可以在绑定中使用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
    }
}

在你的绑定上使用这个:

<Resources>
    <local:MyEnumValueConverter x:Key="myEnumConverter"/>
</Resources>
<ListView ItemsSource="{Binding Converter={StaticResource myEnumConverter}}"/>

这样,您的 ViewModel 可以继续使用枚举,并且用户会看到一个不错的价值。

希望这会有所帮助...

编辑:更新示例以使用问题中提供的 Enum :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多