[英]Why can't I access instance properties in the Execute delegate of a DelegateCommand?
我习惯于以明显不同的方式使用lambdas。 当我尝试定义DelegateCommand
,我必须访问该命令的封闭类型的非静态成员。 例如:
public ICommand ShowViewCommand { get; set; } = new DelegateCommand<string>(v =>
{
var viewModel = new EditFormViewModel;
var ucType = Assembly.GetExecutingAssembly().GetType(v);
App.SetWindowView(viewModel, ucType);
},
v => true);
在上面的代码中,在App.SetWindowView
调用中, App
有一个红色的波浪形下划线,并且在它上面悬停时,我被告知:
无法在静态上下文中访问非静态属性
App
。
这不是我在使用lambda用于闭包时习惯的行为。 这有什么不同?
您正在尝试访问自动实现的属性初始值设定项中的实例成员。 这就像在字段初始化程序中尝试这样做。 基本上,你甚至不能在初始化器中隐式引用this
,甚至在lambda表达式中也是如此。 相反,您需要在构造函数中执行此操作:
public ICommand ShowViewCommand { get; set; }
public Foo() // Replace with your class name
{
ShowViewCommand = v => new DelegateCommand<string>(v =>
{
var viewModel = new EditFormViewModel;
var ucType = Assembly.GetExecutingAssembly().GetType(v);
App.SetWindowView(viewModel, ucType);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.