分配UI权限WPF动态[重复](Assign UI Permissions WPF dynamica

2019-07-17 19:11发布

可能重复:
设置WPF UI权限的代码背后

我开始用WPF工作,并希望创建一个应用程序,将显示根据用户(AD)/隐藏控件和他的角色(S)(自定义)。

我设法通过使用类继承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;
    }
}

而在XAML我添加以下绑定的可见性:

能见度=“{绑定源= {X:静态systhread:} Thread.CurrentPrincipal中,ConverterParameter =管理员;编辑;只读的,转换器= {RV:RoleToVisibilityConverter}}

注:我还需要添加的xmlns:systhread = “CLR的命名空间:的System.Threading;装配= mscorlib程序” 的MainWindow.xaml。

我的问题是:

是上面的例子来做到这一点或(我想)动态动态加载的知名度绑定的最佳途径。

任何帮助,将不胜感激。

诺埃尔。

Answer 1:

你可以尝试使用行为来代替。 我创建了一些简单的代码,你可以看看通过:

public class Permission
{
    private List<string> roles = new List<string>();
    public List<string> Roles
    {
        get { return roles; }
        set { roles = value; }
    }
}

public class PermissionBehavior
{
    // Static behaviour parameters
    public static readonly Dictionary<FrameworkElement, PermissionBehavior> Instances = new Dictionary<FrameworkElement, PermissionBehavior>();

    public static readonly DependencyProperty PermissionProperty =
        DependencyProperty.RegisterAttached("Permission", typeof(Permission), typeof(PermissionBehavior),
                                            new PropertyMetadata(OnPermissionPropertyChanged));

    public static readonly DependencyProperty RoleProperty =
        DependencyProperty.RegisterAttached("Role", typeof(string), typeof(PermissionBehavior),
                                            new PropertyMetadata(OnRolePropertyChanged));

    private static void OnPermissionPropertyChanged(DependencyObject dependencyObject,
                                                  DependencyPropertyChangedEventArgs e)
    {
        SetPermission(dependencyObject, (Permission) e.NewValue);
    }

    public static void SetPermission(DependencyObject obj, Permission value)
    {
        var behavior = GetAttachedBehavior(obj as FrameworkElement);
        behavior.AssociatedObject = obj as FrameworkElement;
        obj.SetValue(PermissionProperty, value);

        behavior.CurrentPermission = value;
        behavior.UpdateVisibility();
    }

    public static object GetPermission(DependencyObject obj)
    {
        return obj.GetValue(PermissionProperty);
    }

    private static void OnRolePropertyChanged(DependencyObject dependencyObject,
                                                  DependencyPropertyChangedEventArgs e)
    {
        SetRole(dependencyObject, (string) e.NewValue);
    }

    public static void SetRole(DependencyObject obj, string value)
    {
        var behavior = GetAttachedBehavior(obj as FrameworkElement);
        behavior.AssociatedObject = obj as FrameworkElement;
        obj.SetValue(RoleProperty, value);

        behavior.RoleList = value.Split(',').ToList();
        behavior.UpdateVisibility();
    }

    public static object GetRole(DependencyObject obj)
    {
        return obj.GetValue(RoleProperty);
    }

    private static PermissionBehavior GetAttachedBehavior(FrameworkElement obj)
    {
        if (!Instances.ContainsKey(obj))
        {
            Instances[obj] = new PermissionBehavior { AssociatedObject = obj };
        }

        return Instances[obj];
    }

    static PermissionBehavior()
    {

    }

    // Class instance parameters
    private FrameworkElement AssociatedObject { get; set; }
    private Permission CurrentPermission { get; set; }
    private List<string> RoleList { get; set; }

    private void UpdateVisibility()
    {
        if(RoleList == null || CurrentPermission == null)
            return;

        if (RoleList.Intersect(CurrentPermission.Roles).Any())
        {
            AssociatedObject.Visibility = Visibility.Visible;
            AssociatedObject.IsEnabled = true;
        }
        else
        {
            AssociatedObject.Visibility = Visibility.Hidden;
            AssociatedObject.IsEnabled = false;
        }
    }
}

XAML

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
            <Button Content="Requires Admin" Margin="6" my:PermissionBehavior.Permission="{Binding UserPermission, Mode=TwoWay}" my:PermissionBehavior.Role="Admin"/>
            <Button Content="Requires User" Margin="6" my:PermissionBehavior.Permission="{Binding UserPermission, Mode=TwoWay}" my:PermissionBehavior.Role="User"/>
        </StackPanel>
        <Button Content="Change user" HorizontalAlignment="Left" Margin="10,88,0,0" VerticalAlignment="Top" Width="75" Click="ButtonBase_OnClick"/>

    </Grid>
</Window>

public partial class MainWindow : Window, INotifyPropertyChanged
{

    private Permission userPermission;

    public Permission UserPermission
    {
        get { return userPermission; }
        set
        {
            userPermission = value;
            OnPropertyChanged("UserPermission");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        UserPermission = new Permission {Roles = new List<string>{"Admin","DumbUser"}};
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var p = new Permission();
        p.Roles = new List<string> {"User", "Supervisor"};
        UserPermission = p;
    }
}

这是微不足道的改变我的权限对象和逻辑与你用什么,我想。



文章来源: Assign UI Permissions WPF dynamically [duplicate]