简体   繁体   中英

Why can't I access instance properties in the Execute delegate of a DelegateCommand?

I'm used to using lambdas in ways apparently other than this. When I try and define a DelegateCommand , I have to access to non-static members of the enclosing type for the command. Eg:

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);

In the above code, in the App.SetWindowView call, App has a red squiggly underline, and on hovering over it, I am told:

Cannot access non-static property App in static context.

This is not the behaviour I'm used to when using lambdas for closures. What is different here?

You're trying to access an instance member within an auto-implemented property initializer. That's like trying to do so in a field initializer. Basically, you can't reference this even implicitly in initializers, not even within lambda expressions. Instead, you'll need to do that in a constructor:

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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM