您可以创建附加属性来确定每个控件的访问级别
public class VisibilitySecurityLevel
{
public static readonly DependencyProperty SecurityLevelProperty =
DependencyProperty.RegisterAttached("SecurityLevel", typeof(int), typeof(FrameworkElement), new PropertyMetadata(5));
public static void SetSecurityLevel(UIElement element, int value)
{
element.SetValue(SecurityLevelProperty, value);
}
public static int GetSecurityLevel(UIElement element)
{
return (int)element.GetValue(SecurityLevelProperty);
}
}
将其应用于您希望由用户角色管理的控件
<Button local:VisibilitySecurityLevel.SecurityLevel="3"/>
<CheckBox local:VisibilitySecurityLevel.SecurityLevel="2"/>
使用基本隐式样式,该样式将使用转换器根据其安全级别绑定控件的可见性
<local:AccessLevelToVisibilityConverter x:Key="AccessLevelToVisibilityConverter"/>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="UserRole"/>
<Binding RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
转换器:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
int userRole = (int)values[0];
int controlAccessLevel = (int)(values[1] as FrameworkElement).GetValue(VisibilitySecurityLevel.SecurityLevelProperty);
return (userRole <= controlAccessLevel) ? Visibility.Visible : Visibility.Hidden;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
请注意,在我的实现中,最低用户角色 5 是最受限制的角色(只能看到访问级别为 5 的控件),而用户角色 1 是最高权限的(可以看到访问级别为 1 -5 的控件)。这就是为什么默认访问级别是 5 ( ) 并且转换器绑定到viewModel 中new PropertyMetadata(5)
的整数属性,指示用户的访问权限 (1 - 5)UserRole
希望这可以帮助