Using enum in ConverterParameter

29,073

Solution 1

ArsenMkrt's answer is correct,

Another way of doing this is to use the x:Static syntax in the ConverterParameter

<Button ...
        Visibility="{Binding Path=CurrentAuthenticationLevel,
            Converter={StaticResource AuthenticationToVisibility},
            ConverterParameter={x:Static local:AuthenticationEnum.Administrator}}"/>

And in the converter

public class AuthenticationToVisibility : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        AuthenticationEnum authenticationEnum = (AuthenticationEnum)parameter;
        //...
    }
}

Solution 2

User

 (AuthenticationEnum)Enum.Parse(typeof(AuthenticationEnum),parameter)

to parse string as enumerator

Share:
29,073

Related videos on Youtube

Leonid
Author by

Leonid

Updated on July 30, 2021

Comments

  • Leonid
    Leonid almost 3 years

    I am building an application that can be used by many users. Each user is classified to one of the next Authentication levels:

    public enum AuthenticationEnum
    {
        User,
        Technitian,     
        Administrator,
        Developer
    }
    

    Some controls (such as buttons) are exposed only to certain levels of users. I have a property that holds the authentication level of the current user:

    public AuthenticationEnum CurrentAuthenticationLevel { get; set; }
    

    I want to bind this property to the 'Visibilty' property of some controls and pass a parameter to the Converter method, telling it what is the lowest authentication level that is able to see the control. For example:

    <Button Visibility="{Binding Path=CurrentAuthenticationLevel, Converter={StaticResource AuthenticationToVisibility}, ConverterParameter="Administrator"}"/>
    

    means that only 'Administrator' and 'Developer' can see the button. Unfortunately, the above code passes "Administrator" as a string. Of course I can use switch/case inside the converter method and convert the string to AuthenticationEnum. But this is ugly and prone to maintenance errors (each time the enum changes - the converter method would require a change also).

    Is there a better way to pass a nontrivial object as a parameter?

  • linquize
    linquize about 12 years
    Using enum value directly has better performance than parsing string every time?
  • Teoman shipahi
    Teoman shipahi about 9 years
    How can we do it in Windows Store Apps? Seems like x:Static is not recognizable by this project type.