为什么我不能在DelegateCommand的Execute委托中访问实例属性?

时间:2016-11-21 08:25:55

标签: c# wpf lambda delegates

我习惯于以明显不同的方式使用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用于闭包时习惯的行为。这有什么不同?

1 个答案:

答案 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
    }