如何找到BindingList的父级?

时间:2013-01-23 07:30:58

标签: c# wpf

我的模型如下。

public class FItem
    {
        public FItem()
        {
            FSubsystems = new BindingList<FSubsystem>();            
        }

        public int RecordId { get; set; }
        public string ItemName { get; set; }


        public BindingList<FSubsystem> FSubsystems { get; set; }


    }

    public class FSubsystem
    {
        public int SubSystemID { get; set; }
        public string ItemName { get; set; }
        public int YearID { get; set; }
    }

代码:

FItems = new ObservableCollection<MarketRecord.FItem>();
FItems.CollectionChanged += OnUiCollectionChanged;


        private void OnUiCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                var addedItem = e.NewItems[0] as MarketRecord.FItem;
                if (addedItem != null)
                {
                    addedItem.PropertyChanged += OnColumnModified;

                    if (addedItem.RecordId == 0)
                        modifedItems.Add(addedItem);


                    addedItem.FSubsystems.ListChanged += OnColumnModified;

                }
            }
        }






private void OnColumnModified(object sender, EventArgs e)
     {
        if (sender.GetType().Name == "FItem")
        {
            MarketRecord.FItem modifiedItem = (sender as MarketRecord.FItem);
            if (!modifedItems.Contains(modifiedItem))
                modifedItems.Add(modifiedItem);
        }
        else
        {
            // add parent of the binding list (i.e fitem object ) add it to             modifedItems

// Find parent here 
        }

     }

正如我的代码告诉我需要在OnColumnModified的else子句中找到绑定列表的父级。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您目前构建代码的方式实际上并非如此。

您可以借助匿名方法实现此目的:

addedItem.FSubsystems.ListChanged += (s, e) => OnColumnModified(addedItem, e);

这将注册一个匿名方法作为ListChanged的事件处理程序。引发该事件时,它会丢弃事件的sender参数,而是传入addedItem实例FItem

您可以通过将OnColumnModified更改为此来改善此代码的类型安全性:

private void OnColumnModified(MarketRecord.FItem modifieditem)
{
    if(!modifiedItems.Contains(modifiedItem))
        modifiedItems.Add(modifiedItem);
}

事件注册现在看起来像这样:

addedItem.PropertyChanged += (s, e) => OnColumnModified(addedItem);

addedItem.FSubsystems.ListChanged += (s, e) => OnColumnModified(addedItem);