gpt4 book ai didi

c# - 如何为基础 ViewModel 类中的所有 DelegateCommand 和 DelegateCommand 调用 RaiseCanExecuteChanged

转载 作者:太空狗 更新时间:2023-10-30 00:43:53 25 4
gpt4 key购买 nike

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

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

现在大多数权限都是简单的允许或禁止显示特定 View 。所有这些都实现为 DelegateCommand或者有时作为 DelegateCommand<T>

如果用户有权显示特定 View ,则这些命令的 CanExecute 返回 true。我还有一个保存用户信息和权限的单例 Sessionmanager。

当用户登录时,我使用 EventAggregator 触发一个事件。在所有 ViewModel 的基类中,我订阅该事件并使用反射遍历 DelegateCommand 类型的 VM 的所有公共(public)属性,并为该命令调用 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();
}

}

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

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

最佳答案

您可以检查属性的类型是否派生自 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();
}
}

关于c# - 如何为基础 ViewModel 类中的所有 DelegateCommand 和 DelegateCommand<T> 调用 RaiseCanExecuteChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9403505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com