3

what is a best way to bind enum property to datagrid.currently i am using public property and return enum name from there is there any other way ?

Enumeration

public enum enStatus
{
    Draft = 1,
    Published = 2,
    Started = 3,
    Completed = 4
}

Model

class ModelA
{
  private int statudId;
  public string Status {  get { return Enum.GetName(typeof(enStatus),statudId); }
}

DataGrid

<DataGrid Name="dataGrdAssignments" Style="{StaticResource dataGridManageScreens}" SelectedCellsChanged="dataGrdAssignments_SelectedCellsChanged">
      <DataGrid.Columns>
        <DataGridTextColumn Header="Status" Width="150" Binding="{Binding Status}" ElementStyle="{StaticResource gridElementStyle}" EditingElementStyle="{StaticResource gridEditElementStyle}">
        </DataGridTextColumn>
      </DataGrid.Columns>
</DataGrid>
Mathieu
  • 1,638
  • 2
  • 27
  • 50
Muhammad Faisal
  • 155
  • 2
  • 13

1 Answers1

3

Your approach works, but I'd prefer cleaning up your ViewModel by using a binding converter instead.

public class EnumConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((Enum)value).ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return  null;
    }
}

And in your XAML, something like this:

Binding="{Binding Status, Converter="{StaticResource ResourceKey=enumConverter}}" 

Don't forget to declare your "enumConverter" (or however you'll decide to name it) in the resources section of your xaml file.

Mathieu
  • 1,638
  • 2
  • 27
  • 50