[ACCEPTED]-How to manipulate WPF GUI based on user roles-identity

Accepted answer
Score: 20

Although previous answer will work, to me 3 it looks little ugly to detect visibility 2 in logic objects. I would use converter 1 for that...

<Control Visibility={Binding Path=CurrentPrincipal, Converter={StaticResource RoleToVisibilityConverter}, ConverterParameter=Administrator}/>

And then the converter itself

public class RoleToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var principal = value as Principal;
        if(principal != null) {
            return principal.IsInRole((string)parameter) ? Visibility.Visible : Visibility.Collapsed;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
         throw new NotImplementedException();
    }
}
Score: 1
<Control Visibility={Binding ElementName=ThisWindow, Path=AdministratorVisibility, Mode=OneWay}/>

In your C# code:

public Visibility AdministratorVisibility
{
    get 
    { 
        MyPrincipal.CurrentPrincipal.IsInRole("Administrator") ? Visibility.Hidden : Visibility.Visible; 
    }
}

You can do the same thing 8 for implementing something for IsReadOnly. If the 7 user's role can change (I'm not sure how 6 these user roles work), you can implement 5 INotifyPropertyChanged and do NotifyPropertyChanged("AdministratorVisibility"), otherwise you could probably change 4 the BindingMode to BindingMode.OneTime and skip implementing the notifications.

This 3 probably isn't a whole lot better than what 2 you're doing already, but it's probably 1 as good as you're going to get.

More Related questions