Possible Duplicate:
Setting WPF UI Permissions in Code Behind
I am starting to work with WPF and want to create an application that will show/hide controls depending on the user(AD) and his role(s)(Custom).
I managed to get this working by using a class inheriting MarkupExpension & IValueConverter.
public class RoleToVisibilityConverter : MarkupExtension,IValueConverter
{
public RoleToVisibilityConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var principal = value as GenericPrincipal;
bool IsValidUser = false;
if (principal != null)
{
foreach (String role in parameter.ToString().Split(';'))
{
if (principal.IsInRole(role))
{
IsValidUser = true;
break;
}
}
return IsValidUser ? Visibility.Visible : Visibility.Collapsed;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
And in the XAML I add the following binding for Visibility:
Visibility="{Binding Source={x:Static systhread:Thread.CurrentPrincipal}, ConverterParameter=admin;editor;readonly, Converter={rv:RoleToVisibilityConverter}}
Note: I also need to add xmlns:systhread="clr-namespace:System.Threading;assembly=mscorlib" to the MainWindow.xaml.
My Questions is:
Is the above example the best way to accomplish this or (as I was thinking) to dynamically load the visibility bindings dynamically.
Any help would be appreciated.
Noel.
You could try using a Behavior instead. I created some simple code you can look through:
XAML
Code
It's trivial to change my Permission object and logic with what you use, I would think.