Home > C#, MVVM, WinRT > EnumToVisibilityConverter for Windows Store apps

EnumToVisibilityConverter for Windows Store apps

13/05/2013

Suppose that, in our Windows Store app, we have an Enum like the following:

public enum ResponseState
{
    Valid,
    Invalid,
    NotFound
}

If we’re using the MVVM pattern and we have a ViewModel with a property of that Enum type, we could need to show certain parts of the UI depending on its value. In this case, the simplest solution is to use a converter:

public class EnumToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null || parameter == null || !(value is Enum))
            return Visibility.Collapsed;

        var currentState = value.ToString();
        var stateStrings = parameter.ToString();
        var found = false;

        foreach (var state in stateStrings.Split(','))
        {
            found = (currentState == state.Trim());

            if (found)
                break;
        }

        return found ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
        string language)
    {
        throw new NotImplementedException();
    }
}

The converter will return Visibility.Visible if the parameter argument contains a string equal to value, Visible.Collapsed otherwise.

So, if we want to alternatively show Grid objects depending on the value of a ViewModel property named CurrentResponse (of ResponseState enum type), we can write something like this:

<Grid Visibility="{Binding CurrentResponse,
    Converter={StaticResource EnumToVisibilityConverter},
    ConverterParameter='Valid'}">
    <TextBlock Text="Valid"></TextBlock>
</Grid>

<Grid Visibility="{Binding CurrentResponse,
    Converter={StaticResource EnumToVisibilityConverter},
    ConverterParameter='Invalid, NotFound'}">
    <TextBlock Text="Invalid or NotFound"></TextBlock>
</Grid>

As shown in the example, it is possible to specify more values in the ConverterParameter tag, separated by a comma.

Categories: C#, MVVM, WinRT
%d bloggers like this: