ProfK ProfK - 19 days ago 6
C# Question

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


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?

Answer

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