0

If I define a variable within a method, then subscribe to an event with a Lambda expression, and use the variable within the body of that expression, is the reference still valid? I don't get a compile time error, but it doesn't seem to be working quite as I'd hoped, either.

See:

void OnAddAssignment()
{
    var win = new View.NewTransportationView();
    var vm = new NewTransportationViewModel(DateTime.Today);
    vm.JobSaved += (s, e) => { win.Close(); };

    win.DataContext = new ViewModel.NewTransportationViewModel(DateTime.Today);
    win.WindowStartupLocation = WindowStartupLocation.CenterScreen;

    win.Show();
}

Note: NewTransportationView inherits from System.Windows.Window

I was hoping when JobSaved fires, the window would close, and I wouldn't have to save the reference to the NewTransportationView outside the method.

I realize there are probably dozens of other ways to solve this problem, many or most more elegant and efficient, and while I am certainly open to seeing suggestions, I am more interested in the general behavior and scope rules for this particular application of a Lambda expression.

Bonus question: where do my Window objects live when I call .Show() on them?

Michael
  • 1,803
  • 1
  • 17
  • 26
  • 1
    http://stackoverflow.com/questions/9591476/are-lambda-expressions-in-c-sharp-closures – L.B Nov 30 '12 at 20:00
  • 1
    Did you mean to assign a different instance of the `NewTransportationViewModel` class to the `win.DataContext` property? – Richard Deeming Nov 30 '12 at 20:00
  • @RichardDeeming NOPE! I just noticed this when I returned to my code. Probably in about the same instance of your comment. ;) – Michael Nov 30 '12 at 20:01
  • @L.B Excellent link. Thank you. Did get that with my terms of 'lambda' & 'scope' – Michael Nov 30 '12 at 20:02
  • Well, as soon as I fixed my reference oversight, it works as I'd expected it to, resolving my problem, answering my question, and expanding my knowledge. win, win, win. – Michael Nov 30 '12 at 20:05
  • @Michael For reference, this isn't inelegant at all. It's my favorite approach for solving this type of problem because it works, it clear to the reader, and honestly about as elegant of a solution as I've ever seen. It also comes up quite often. Closures FTW. – Servy Nov 30 '12 at 20:19

0 Answers0