事件未被清除

时间:2014-04-03 21:42:33

标签: c# .net

我正在添加一个已更改的事件或一个可观察的集合。

var someList = new Observablecollection<ITCardBase>();
someList.CollectionChanged+=Changed;

void Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    if(e.Action==System.Collections.Specialized.NotifyCollectionChangedAction.Add)
    {
        if(e.NewItems[0] is ITCardBase)
        {
            ITCardBase eq = (ITCardBase)e.NewItems[0];
            eq.Unsubscribe(TCardClickedInList);
            eq.Subscribe(TCardClickedInList);
        }
    }

}
//this just allows a user control to be clicked and bind to the event
public virtual void Subscribe(Func<ITCardBase, int> myMethodName)
{       
    TCardClick += myMethodName.Invoke;          
}
public virtual void Unsubscribe(Func<ITCardBase, int> myMethodName)
{             
    TCardClick -= myMethodName.Invoke;
}
public int TCardClickedInList(ITCardBase card)
{
    //click event when the user clicks the "card" user control"
    return 0;
}

我遇到的问题是,当我清除列表,然后从我的数据库中重新添加项目时,click事件会被复制,因此它会被调用两次,然后是树时间等等。所以清除SomeList不会似乎删除了它们内部对象的事件,即使它们应该消失了。

我怎样才能正确地清除&#34;列表中的项目,因此当它们再次从数据库中添加时(它们是相同的项目),它不会复制此事件。我试过做一个Unsubscribe(),它不起作用。

修改

 public void ReloadTCards()
    {
        if (SubTCardList != null)
        {

         foreach(ITCardBase card in SubTCardList)
         {
             card.Unsubscribe(TCardClickedInList);
         }//I TRIED unsubscribg each element before I clear the list
          //but then when I readd the items to the list, the same issue happens

            SubTCardList.Clear();
            LoadSubTCardsWithIncidentID(TCardLoadedIncidentId);
        }

    }

1 个答案:

答案 0 :(得分:0)

  public virtual void Subscribe(Func<ITCardBase, int> myMethodName)
    {

        TCardClick = null;//THIS FIXED EVERYTHING
        TCardClick += myMethodName.Invoke;          
    }

我只是将事件置空,因为在第二次调用subscribe时(当列表再次被添加时),这不是null,因为这是第一次。