如何在基本ViewModel类中为所有DelegateCommand和DelegateCommand <T>调用RaiseCanExecuteChanged

Mic*_* D. 4 c# reflection wpf mvvm delegatecommand

我正在使用Prism和MVVM开发WPF应用程序.

该应用程序的要求之一是能够以不同的用户身份登录(具有不同的权限).

现在大多数权限都是简单的允许或禁止显示特定视图.所有这些都是在DelegateCommand某个时间实现的DelegateCommand<T>

如果用户有权显示特定视图,那么这些命令的CanExecute将返回true.我还有一个包含用户信息和权限的单一Sessionmanager.

当用户登录时,我使用EventAggregator触发事件.在所有ViewModel的基类中,我订阅了该事件,并使用了反射循环通过类型为DelegateCommand的VM的所有公共属性,并为该命令调用RaiseCanExecuteChanged.

        Type myType = this.GetType();
        IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

        foreach (PropertyInfo prop in props)
        {
            if (prop.PropertyType == typeof(DelegateCommand))
            {
                var cmd = (DelegateCommand)prop.GetValue(this, null);
                cmd.RasieCanExecuteChanged();
            }

        }
Run Code Online (Sandbox Code Playgroud)

这适用于所有非泛型DelegateCommand属性,但当然不会影响DelegateCommand<T>.

我的问题是如何确定属性是否为类型DelegateCommand<T>并转换为该特定类型才能调用RasieCanExecuteChanged?

Adi*_*ter 7

您可以检查属性的类型是否来自DelegateCommandBase,如果是,则将其转换为DelegateCommandBase并调用RaiseCanExecuteChanged.

Type myType = this.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    if (prop.PropertyType.IsSubclassOf(typeof(DelegateCommandBase)))
    {
        var cmd = (DelegateCommandBase)prop.GetValue(this, null);
        cmd.RaiseCanExecuteChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)