我习惯于以明显不同的方式使用lambdas。当我尝试定义DelegateCommand
时,我必须访问该命令的封闭类型的非静态成员。 E.g:
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用于闭包时习惯的行为。这有什么不同?
答案 0 :(得分:7)
您尝试访问自动实现的属性初始值设定项中的实例成员。这就像在字段初始化程序中尝试这样做。基本上,您甚至不能在初始化程序中隐式引用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);
});
}
。相反,您需要在构造函数中执行此操作:
Slider {
id: sliderHorizontal1
x: 69
y: 52
activeFocusOnPress: true
tickmarksEnabled: true
minimumValue: 0
}