WPF wpf中按钮操作权限控制

原文: WPF wpf中按钮操作权限控制

权限控制我们有很多种方式可以实现。

这次项目中做个简单的权限控制,我们在所有按钮触发前判断,有权限则可执行。

我们自定义一个命令类。

 public class DelegateCommand : ICommand
    {
        Action _action;
        Func<bool> _canAction;
        string _Role;
        public DelegateCommand(Action action,string Role=null)
        {
            _Role = Role;
            _action = action;
        }

        public DelegateCommand(Action action, Func<bool> canAction, string Role = null)
        {
            _Role = Role;
            _action = action;
            _canAction = canAction;
        }

        public bool CanExecute(object parameter)
        {
            if (_canAction == null)
            {
                return true;
            }
            return _canAction.Invoke();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }
          

        public void Execute(object parameter)
        {
            if (_action != null)
            {
                if (_Role!=null)
                {
                   if ( System.Windows.MessageBox.Show("此权限为"+_Role,"",System.Windows.MessageBoxButton.OKCancel)!= System.Windows.MessageBoxResult.OK)
                    {
                        return;
                    }
                }
                _action.Invoke();
            }
        }

在Execute时验证权限

用的时候将此按钮的权限对象传入Command

AbnormalCommand = new DelegateCommand<string>((p) => Messenger.Default.Send<string>(p, "HomeNavgation"),"Abnormal Button Role");

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/11112123.html
WPF