ArcEngine GroupLayer监听图层改变

时间:2024-04-04 12:33:21

最近项目中需要用到在TOC监听图层的变化,从而针对添加的不同图层进行不同的操作。但是当TOC中添加图层组时,无法监听到图层组中添加图层的动作。也就无法获取到向图层组中添加的图层。

在开发手册中也没有找到相应的事件接口来实现。于是就动手自己写了一个事件监听。

实现的思路是,自己构建事件接口,然后构建一个GroupLayer的子类来实现这个接口。

具体看代码:

///////////////////////////////
/////// 事件接口的代码
// 构建图层组图层增加的委托
public delegate void IGroupLayerEvents_ItemAddedEventHandler(object Item);
// 构建图层组图层移除的委托
public delegate void IGroupLayerEvents_ItemDeletedEventHandler(object Item); // 构建图层组事件接口
public interface IGroupLayerEvents
{
// 增加项事件
event IGroupLayerEvents_ItemAddedEventHandler ItemAdded;
// 移除项事件
event IGroupLayerEvents_ItemDeletedEventHandler ItemDeleted;
}
////////////
///构建GroupLayerClass的子类
// 构建GrouplayerClassEx类继承Esri的GroupLayer并实现自定义的IG肉pLayerEvents接口
public class GroupLayerClassEx:GroupLayerClass,IGroupLayerEvents
{
#region IGroupLayerEvents 成员
public event IGroupLayerEvents_ItemAddedEventHandler ItemAdded;
public event IGroupLayerEvents_ItemDeletedEventHandler ItemDeleted;
#endregion // 重写添加的方法
public override void Add(ILayer layer)
{
base.Add(layer);
// 实现事件
if (ItemAdded != null)
{
ItemAdded(layer);
}
} // 重写清除的方法
public override void Clear()
{
// 遍历图层实现项减少的事件
if (ItemDeleted != null)
{
ICompositeLayer pCompositeLayer = this as ICompositeLayer;
for (int i = 0; i < pCompositeLayer.Count; i++)
{
ILayer pCurrentLayer = pCompositeLayer.get_Layer(i);
ItemDeleted(pCurrentLayer);
}
}
base.Clear();
} // 重写删除的方法
public override void Delete(ILayer Layer)
{
base.Delete(Layer);
if (ItemDeleted != null)
{
ItemDeleted(Layer);
}
}
···
其他IGroupLayer接口实现的方法和属性都要override一遍。
···
}

在地图控件事件中进行监听

 private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
{
AxMapControl pAxMapControl = sender as AxMapControl; // 注册事件
mEvent = pAxMapControl.ActiveView.FocusMap as IActiveViewEvents_Event;
mEvent.ItemAdded += new IActiveViewEvents_ItemAddedEventHandler(Event_ItemAdded);
mEvent.ItemDeleted += new IActiveViewEvents_ItemDeletedEventHandler(Event_ItemDeleted);
}
private void Event_ItemAdded(object Item)
{
if (Item is IGroupLayer)
{
IGroupLayerEvents pIGroupLayerEvents = Item as IGroupLayerEvents;
if (pIGroupLayerEvents != null)
{
pIGroupLayerEvents.ItemAdded += new IGroupLayerEvents_ItemAddedEventHandler(Event_ItemAdded);
pIGroupLayerEvents.ItemDeleted += new IGroupLayerEvents_ItemDeletedEventHandler(Event_ItemDeleted);
}
}
}