简体   繁体   English

奇怪的silverlight事件行为

[英]Strange silverlight event behaviour

Im a noob at silverlight and .net. 我是银光和.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.Children.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. 当我第一次按下按钮时,它会移除stackpanel子,然后退出,我必须再次按下它以删除另一个对象。 Anybody have an explanation why ? 有人解释为什么?

Does s actually contain a list of objects? s实际上是否包含对象列表?

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. 您正在选择r.Id == Id项目,并且不知道Id是什么以及它来自何处,看起来您的代码应该只返回单个项目。

Once you've got past the fact you're only selecting one item with a matching ID, you'll probably have another problem. 一旦你超越了事实,你只选择一个具有匹配ID的项目,你可能会遇到另一个问题。 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. 你在迭代它时修改了集合ctrl.Children,这打破了整个枚举模式。 (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. Linq查询生成您可以将其视为装饰枚举器,指向原始集合。 Forcing s to be a seperate collection by calling ToList or ToArray will fix this. 通过调用ToList或ToArray强制s成为一个单独的集合将解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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