gpt4 book ai didi

c# - ListView 和枚举

转载 作者:行者123 更新时间:2023-11-30 22:39:34 25 4
gpt4 key购买 nike

我经常需要处理用户界面中的列表,这些列表会转换为“ViewModel”中的枚举值。我知道我可以通过提供枚举项名称的 ObjectDataProviderListView.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com