Xamarin UIButton 有多个事件处理程序

Xamarin UIButton has multiple event handlers

我 运行 遇到一个问题,单元格中的 UIButtons 在 Xamarin 中分配了多个事件处理程序。有没有办法确保只分配一个事件处理程序?我假设在重新加载 tableview 或 collectionview 时,这些单元格中的任何内容都是 released/reset。这不正确吗?

这里是我在委托中设置单元格的地方:

public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            EventHandler clickTarget = (sender, e) =>
            {
                if (this.parantController.showCategories)
                {
                    this.parantController.apiCallGetBusinessesIndustries(this.parantController.businessesCategoriesResponseModel.business_categories[indexPath.Row].id);
                    this.parantController.showIndustries = true;
                    this.parantController.showCategories = false;
                }
                else  if (this.parantController.showIndustries)
                {
                    this.parantController.apiCallGetBusinessessList("", this.parantController.businessesIndustriesResponseModel.business_industries[indexPath.Row].id);
                    this.parantController.filterView.Hidden = true;
                    this.parantController.showVerticalList = false;
                    this.parantController.showIndustries = false;
                    this.parantController.clearAll = true;
                    this.parantController.filterCollectionView.ReloadData();
                    this.parantController.clearAll = false;
                    //this.parantController.showCategories = true;
                }
            };

            var cell = (FilterCollectionCell)collectionView.DequeueReusableCell("filterCollectionCell", indexPath);
            if (this.parantController.businessesCategoriesResponseModel.business_categories != null && !this.parantController.showIndustries)
            {
                cell.updateCell(false, this.parantController.businessesCategoriesResponseModel.business_categories[indexPath.Row].name, clickTarget);
            }
            if (this.parantController.showIndustries)
            {
                cell.updateCell(false, this.parantController.businessesIndustriesResponseModel.business_industries[indexPath.Row].name, clickTarget);
            }

            return cell;
        }

这是我将事件处理程序添加到单元格视图控制器中的按钮的代码:

public void updateCell(Boolean selectedFilterType, string title, EventHandler clickHandler) {

        btnFilter.RemoveTarget(this, null, UIControlEvent.AllEvents);

        btnFilter.AddTarget(clickHandler, UIControlEvent.TouchUpInside);// = handlerToUse;

        this.btnFilter.SetTitle(title, UIControlState.Normal);
    }

您的 FilterCollectionCell 创建应该处理将事件应用于单元格,因此当重复使用单元格时,您不会在 GetCell 方法中每次都附加新事件。

否则,您可以检索所有 UButton 的目标并在每次请求单元格时删除它们:

foreach (var target in button.AllTargets)
{
    button.RemoveTarget(target, null, UIControlEvent.AllTouchEvents);
}