简体   繁体   中英

How to Display a friendly enum name in WPF datagrid

I've noticed that the WPF DataGrid displays the Enum Name by default. This is great. But is there a way to display a more friendly name? ie Without these underscores in my case?

在此处输入图片说明

void ResultGrid_AutoGeneratingColumns(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {


            if (e.Column.GetType() == typeof(DataGridComboBoxColumn))
            {
                var binding = (e.Column as DataGridComboBoxColumn).TextBinding.StringFormat(...);
              //  binding.Converter = new EnumConverter();
            }
        }

You can write a custom IValueConverter to take your enum value and return a friendly string. This just does a simple string replace.

public class GeneralEnumConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value.GetType().IsEnum)
        {
            return this.FormatEnumName(value.ToString());
        }

        return null;
    }

    private string FormatEnumName(string enumName)
    {
        return enumName.Replace('_', ' ');
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Then your XAML will need a resource:

<UserControl.Resources>
    <Converter:GeneralEnumConverter x:Key="GeneralEnumConverter"/>
</UserControl.Resources>

You will need to define Converter in your XAML root element and point it to the namespace for your converter. This is a lot easier if done in Blend/Visual Studio XAML Designer as you can create a new converter from the 'Create Binding' menu.

Next apply the converter to your binding...

<Label x:Name="label" Content="{Binding Tag, Converter={StaticResource GeneralEnumConverter}, ElementName=label}" />

This is a hacky binding of a label to itself, the important part is the Converter= attribute.

Hope this helps.

Please mark as answer if so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM