gawicks
gawicks

Reputation: 1964

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? i.e. Without these underscores in my case?

enter image description here

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();
            }
        }

Upvotes: 2

Views: 3420

Answers (1)

kidshaw
kidshaw

Reputation: 3451

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.

Upvotes: 2

Related Questions