枚举的组合框转换器

发布于 2024-12-12 06:09:31 字数 348 浏览 1 评论 0原文

我有一个枚举,其中包含

HomeRun、StolenBase、FirstBase 等值。

我想在组合框中显示这些值,并在大写字母之前插入一个空格,因此它将显示为“Home Run”、“Stolen Base”, 我已经有了可以为我进行格式化的

代码,并且我已将该代码添加到 IValueConverter 实现的“Convert”方法中。

我的问题是,我需要在哪里使用这个转换器(在 xaml 中),这样不仅下拉列表,而且显示的值也将具有这种格式?我还需要实施 ConvertBack 吗?

我很清楚为枚举设置“描述”并使用流行的 EnumToDescriptionConverter,但我宁愿远离它。

I have an enumeration that has values like

HomeRun, StolenBase, FirstBase, etc.

I want to display these values in a combobox, with a space inserted before the capital letters, so it will display as 'Home Run', 'Stolen Base', etc.

I already have code that can do the formatting for me, and I have added that code to the 'Convert' method of an IValueConverter implementation.

My question is, where do I need to use this converter (in the xaml) such that not only the dropdown, but also the displayed value, will have this formatting? Do I need to implement ConvertBack as well?

I am well aware of setting 'descriptions' for the enumeration and using the popular EnumToDescriptionConverter, but I'd rather stay away from that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

苏别ゝ 2024-12-19 06:09:31

我不确定是否有更好的方法,但您可以使用 ItemTemplate 实现您想要的效果,

<ComboBox.ItemTemplate>
    <DataTemplate>
        <ContentPresenter
            Content="{Binding Converter={StaticResource baseballEnumConverter}}"/>
     </DataTemplate>
</ComboBox.ItemTemplate>

这将在您的 ComboBox 中显示转换后的值。

ComboBox 的 SelectedValue 仍将是 Enum 值。您不需要实施 ConvertBack。

I'm not sure if there is a better way, but you can achieve what you want using an ItemTemplate

<ComboBox.ItemTemplate>
    <DataTemplate>
        <ContentPresenter
            Content="{Binding Converter={StaticResource baseballEnumConverter}}"/>
     </DataTemplate>
</ComboBox.ItemTemplate>

This will display the converted value in your ComboBox.

The SelectedValue of the ComboBox will still be the Enum value. You won't need to implement ConvertBack.

作死小能手 2024-12-19 06:09:31

[更新] 我的答案的关键点是枚举值完全转换。我认为这种方式比隐藏每个枚举值更容易。[/updated]

我需要在哪里使用这个转换器(在xaml中),这样不仅下拉列表,而且显示的值,都会有这个
格式化?

在 ComboBox 的 Binding ItemsSource(ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}}") 处,请检查以下代码。

我还需要实现 ConvertBack 吗?

不,你不需要。,因为在运行时你无法修改枚举,即使可以修改枚举,你也无法更改 VIEW 中 ComboBox 的 ItemsSource,这意味着 Binding Mode 是 OneWay。

XAML

<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MyEnumConverter x:Key="converter"/>
    </Window.Resources>
    <StackPanel>
        <ComboBox ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}, Mode=OneWay}"></ComboBox>
    </StackPanel>
</Window>

代码

public enum MyEnum
{
    HomeRun, StolenBase, FirstBase
}

[ValueConversion(typeof(object), typeof(List<string>))]
public class MyEnumConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var names = Enum.GetNames(typeof (MyEnum)).ToArray();
        //Add some code to support the thing you want to do(add blank in front of Capital...)
        return names;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

[updated] The key point of my answer is that the enum values are converted totally. I think this way is eaier than the coverting each enum value.[/updated]

Where do I need to use this converter (in the xaml) such that not only the dropdown, but also the displayed value, will have this
formatting?

At Binding ItemsSource of ComboBox(ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}}"), Please check the following code.

Do I need to implement ConvertBack as well?

No, you don't., because at runtime you cannot modify the enumeration, and even though it can do, you cannot change ItemsSource of ComboBox in VIEW, which means Binding Mode is OneWay.

XAML

<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MyEnumConverter x:Key="converter"/>
    </Window.Resources>
    <StackPanel>
        <ComboBox ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}, Mode=OneWay}"></ComboBox>
    </StackPanel>
</Window>

Code

public enum MyEnum
{
    HomeRun, StolenBase, FirstBase
}

[ValueConversion(typeof(object), typeof(List<string>))]
public class MyEnumConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var names = Enum.GetNames(typeof (MyEnum)).ToArray();
        //Add some code to support the thing you want to do(add blank in front of Capital...)
        return names;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
白况 2024-12-19 06:09:31

如果您希望将 ComboBox 的选定值转换回为枚举,那么您需要实现ConvertBack

我个人会选择您提到的描述属性模式,因为

  1. 已经提出了明显的问题,并且
  2. 您不仅限于简单地在大写字母处插入空格 - 您可以使用您想要的任何描述。

但假设您想采用这种模式,您只需要正确编写转换器即可。我建议这样:

// Convert method
var formattedNames = new List<string>();
foreach (var value in Enum.GetValues(typeof(Things)))
{
    // Format is a method to convert the enum value to the display string
    var formattedName = Format(value);
    formattedNames.Add(formattedName);
}
// return a list of strings that you can bind to
return formattedNames;

// ConvertBack method
// Unformat is a method to revert the display string back to the enum value
var value = Unformat(formattedValue);
return Enum.Parse(typeof(Things), value);

您还可以创建一个简单的类来保存显示值和枚举,然后适当地设置组合框上的 DisplayPath 属性

class DisplayEnum
{
    public string DisplayValue { get;set; }
    public MyEnum ActualValue { get;set; }
}

<ComboBox DisplayMemberPath=DisplayValue ...

编辑

我意识到这不起作用,因为 ConvertBack 正在尝试将字符串转换为枚举,但实际的绑定集是 List。我将把它留在这里,因为这是一个正确方向的开始。

我相信您需要两个转换器

  1. 将枚举类型转换为一组枚举值,并将
  2. 枚举值转换为字符串。第二个转换器应实现 ConvertBack 方法。

正如我所指出的,如果您不实现 ConvertBack ,那么您将无法将 SelectedValue 绑定回 ViewModel 上的枚举属性。

If you want the selected value of the ComboBox to be converted back to an enum then you will need to implement ConvertBack.

I'd personally go with the description attribute pattern that you mentioned, because

  1. the obvious questions have already been asked, and
  2. You aren't limited to simply inserting spaces at uppercase letters - you can use whatever description you want.

But assuming you want to go with this pattern, you just need to write your converter correctly. I'd suggest something like this:

// Convert method
var formattedNames = new List<string>();
foreach (var value in Enum.GetValues(typeof(Things)))
{
    // Format is a method to convert the enum value to the display string
    var formattedName = Format(value);
    formattedNames.Add(formattedName);
}
// return a list of strings that you can bind to
return formattedNames;

// ConvertBack method
// Unformat is a method to revert the display string back to the enum value
var value = Unformat(formattedValue);
return Enum.Parse(typeof(Things), value);

You could also create a simple class to hold both the display value and the enum, and then set the DisplayPath property on the combo box appropriately

class DisplayEnum
{
    public string DisplayValue { get;set; }
    public MyEnum ActualValue { get;set; }
}

<ComboBox DisplayMemberPath=DisplayValue ...

Edit

I realise that this won't work because the ConvertBack is attempting to convert a string to an enum, but the actual binding set is a List<string>. I'll leave it here because it is a start in the right direction.

I believe you'd need two converters

  1. to convert the enum type into a set of enum values, and
  2. to convert an enum value to a string. This second converter should implement the ConvertBack method.

As I pointed out, if you don't implement ConvertBack then you won't be able to bind the SelectedValue back to your enum Property on your ViewModel.

杀手六號 2024-12-19 06:09:31

您将需要创建一个字典或其他一些查找结构,将枚举值映射到字符串表示形式。

You will need to make a dictionary or some other lookup structure that maps the Enum value to the string representation.

浮光之海 2024-12-19 06:09:31

有一个提示可以作为开始:

http://geekswithblogs .net/jawad/archive/2005/06/24/EnumDropDown.aspx

我开发了自己的枚举绑定助手从这个想法开始。

There is an hint that you can use as a start :

http://geekswithblogs.net/jawad/archive/2005/06/24/EnumDropDown.aspx

I developped my own enum binding helpers starting with that idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文