5.调用属性表窗体
通过1-4步骤,我们封装了一个AttributeTableFrm类,此类能够由ILayer显示图层中的属性表数据。那怎么调用AttributeTableFrm呢?
前面已经提到,我们是在TOCControl选中图层的右键菜单中弹出属性表窗体的,因此我们需要添加一个菜单项到TOCControl中Layer的右键菜单。而在第六讲中,我们采用的是AE中的IToolbarMenu实现右键菜单的,故我们还需自定义一个Command,实现打开属性表的功能。
以ArcGIS的Base Command为模板新建项“OpenAttributeTable.cs”。
注意:新建Base Command模板时,会弹出一个对话框让我们选择模板适用对象,这时我们要选择MapControl、PageLayoutControl,即选择第二项或者倒数第二项。
添加如下引用:
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; |
添加成员变量:
private ILayer m_pLayer; |
修改构造函数为:
public OpenAttributeTable(ILayer pLayer)
{ // // TODO: Define values for the public properties // base.m_category = ""; //localizable text base.m_caption = "打开属性表"; //localizable text base.m_message = "打开属性表"; //localizable text base.m_toolTip = "打开属性表"; //localizable text base.m_name = "打开属性表"; //unique id, non-localizable (e.g. "MyCategory_MyCommand") m_pLayer = pLayer; try { // // TODO: change bitmap name if necessary // string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } |
再在On_Click函数中添加如下代码,以创建并打开属性表窗体。
/// <summary>
/// Occurs when this command is clicked /// </summary> public override void OnClick() { // TODO: Add OpenAttributeTable.OnClick implementation AttributeTableFrm attributeTable = new AttributeTableFrm(); attributeTable.CreateAttributeTable(m_pLayer); attributeTable.ShowDialog(); } |
至此,我们完成了OpenAttributeTable命令。显然,我们要在TOCControl的OnMouseDown事件中调用此命令。
因为,当前选中的图层参数,即ILayer是通过OpenAttributeTable的构造函数传入的,而选中的ILayer是动态变化的,所以我们无法在窗体初始化的Form1_Load事件中就添加OpenAttributeTable菜单项到右键菜单。但我们可以在OnMouseDown事件中动态添加OpenAttributeTable菜单项。
要注意的是,最后我们必须移除添加的OpenAttributeTable菜单项,不然每次按下右键都会添加此菜单项,将造成右键菜单中含有多个OpenAttributeTable菜单项。
修改TOCControl的OnMouseDown事件的部分代码如下:
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
{ //…… //弹出右键菜单 if (item == esriTOCControlItem.esriTOCControlItemMap) m_menuMap.PopupMenu(e.x, e.y, m_tocControl.hWnd); if (item == esriTOCControlItem.esriTOCControlItemLayer) { //动态添加OpenAttributeTable菜单项 m_menuLayer.AddItem(new OpenAttributeTable(layer), -1, 2, true, esriCommandStyles.esriCommandStyleTextOnly); m_menuLayer.PopupMenu(e.x, e.y, m_tocControl.hWnd); //移除OpenAttributeTable菜单项,以防止重复添加 m_menuLayer.Remove(2); } } |
6.编译运行
按下F5,编译运行程序,相信你已经实现了开篇处展示的属性表效果了吧!
以上代码在Windows XP Sp3 + VS2005 + AE9.2环境下编译通过。