Im a noob at silverlight and .net. Just started playing with them and I've got an event attached to a custom control that behaves strangely. This would be the handler code:
private void clickCloseWindow(object sender, RoutedEventArgs e)
{
StackPanel ctrl = (StackPanel)FindName("WindowsPanel");
var s = from r in ctrl.Children.OfType<BarWindowTab>() where r.Id==Id select r;
foreach (BarWindowTab b in s)
{
ctrl.Childre开发者_如何学运维n.Remove(b);
}
parent.Children.Remove(this);
}
As u can see, I'm trying to remove several objects from screen. The thing is, the handler exits after each removal for some reason instead of removing them all at once. When I press the button first time, it removes the stackpanel child, then it exits and I have to press it again to remove the other object. Anybody have an explanation why ?
Does s
actually contain a list of objects?
You are selecting items where r.Id == Id
and without knowing what Id
is and where it comes from it looks like your code should only return a single item.
Once you've got past the fact you're only selecting one item with a matching ID, you'll probably have another problem. I imagine if you attach a debugger and catch exceptions you'll discover one will get thrown :)
You're modifying the collection ctrl.Children as you iterate through it, which breaks the whole enumeration pattern. (Remove one item -> try to move to next -> "oh pants, the collection has changed")
Linq queries generate what you can think of as a decorated enumerator, pointing to the original collection. Forcing s to be a seperate collection by calling ToList or ToArray will fix this.
精彩评论