Search code examples
c#.netwpfenumsivalueconverter

IValueConverter removing underlying value of enum(int)


I'm passing an Enum with underlying value (int) as a parameter from XAML to an IValueConverter. The idea is to use the Enum value to iterate against a list to check if the value exists & return a Visibility enum. The list is of type int. But when passing the Enum to the converter, I cannot cast the Enum back to an int. Peering into the parameter with 'Quick Watch', I cannot see the underlying value or any value at all.

Enum e.g.

public class Operations
{
    public enum Reporting
    {
        ReportAccounts    = 101,
        ReportEngineering = 102,
        ReportSoftware    = 103,
        ReportPR          = 104,
        ReportCRM         = 105
     }
     public enum Editing
     {
        EditUser   = 201,
        EditAccess = 202,
        EditView   = 203
     }
 }

XAML e.g.

Visibility={Binding Converter={StaticResource VisibilityConverter}, 
        ConverterParameter={x:Static Operations:Reporting.ReportAccounts}}

IValueConverter e.g.

public object Convert(object value, Type targetType, object parameter, 
                      System.Globalization.CultureInfo culture)
{
     bool visibility = OperationList.Exists(list => list.Id == (int)parameter);
     if (visibility == true)
     {
         return Visibility.Visible;
     }
     else
     {
         return Visibility.Collapsed;
     }
 }

I would like to know if there is any way of retaining or retrieving the underlying value of an enum when it is passed to an IValueConverter.


Solution

  • You might have to cast the parameter to the enum-type Reporting first:

    int val = System.Convert.ToInt32((Reporting)parameter);
    bool visibility = OperationList.Exists(list => list.Id == val);