| פתרון לבעיית הרשמה לאירועים באמצעות Lambda Expression בתוך לולאה

The following is the piece of code from our project in LS(LightSwich) environment;
partial void LanguagesEditableGrid_InitializeDataWorkspace(List saveChangesTo)
{
// Write your code here.

foreach (INotifyPropertyChanged language in Languages)
{
Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
{
language.PropertyChanged += new PropertyChangedEventHandler(language_PropertyChanged);
});
}
}
void language_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//…
}
We have Languages collection where each item is Language. Language implements INotifyPropertyChanged interface.
We try to register every language to PropertyChanged event of INotifyPropertyChanged interface. The registration should run on the UI thread so we do the registration through the LS dispatcher by passing to its BeginInvoke function lambda expression.
But when we run the above code we see that only the last language instance is registered to the event several times (as a number of languages in the collection)…
You can read in the following post the explanation why the code does not work: http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx
To fix the above we should add a local loop variable and use it in the lambda expression.
partial void LanguagesEditableGrid_InitializeDataWorkspace(List saveChangesTo)
{
// Write your code here.

foreach (INotifyPropertyChanged language in Languages)
{
var copy = language;
Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
{
copy.PropertyChanged += new PropertyChangedEventHandler(language_PropertyChanged);
});
}
}

לא ניתן להגיב.