在完成历史演变功能时出现如下情况,即:按照年份初始化图层,在每个初始化的图层中添加要素时报错(要素的Attributes相同)
报错的核心代码如下(注:此处的CustomLayer是继承GraphicsLayer,可直视为GraphicsLayer
此处的myMap是控件Map的ID)
//历史演变第一年,此时没有报错
CustomLayer customLayer = new CustomLayer();
customLayer.Map = RenderEnty.myMap;
customLayer.ID = "LSYB2012";
customLayer.Visible = true;
myMap.Layers.Add(customLayer);
Graphic graphic = (from g in listGraphic where graphic.Attributes["key"].ToString() == strCode select g).FirstOrDefault();
graphic.Symbol = symbol;
customLayer.Graphics.Add(graphic);
//历史演变第二年,此时在红色部分报错
CustomLayer customLayer = new CustomLayer();
customLayer.Map = RenderEnty.myMap;
customLayer.ID = "LSYB2013";
customLayer.Visible = true;
myMap.Layers.Add(customLayer);
Graphic graphic = (from g in listGraphic where graphic.Attributes["key"].ToString() == strCode select g).FirstOrDefault();
graphic.Symbol = symbol;
customLayer.Graphics.Add(graphic);
开始以为这里的问题是由于graphic的属性字段和值一样报错的,于是果断将两次Graphic生成做调整。
Graphic graphic = (from g in listGraphic where graphic.Attributes["key"].ToString() == strCode select g).FirstOrDefault();
graphic.Attributes.Add("id",DateTime.Now.ToString("yyyymmddHHmmssfff"));
graphic.Symbol = symbol;
customLayer.Graphics.Add(graphic);
此时,在第二次执行红色部分的时候就报错,提示“已经添加了相同项”,跟踪代码发现在graphic中已经存在了id这个属性字段。即使对id这个属性字段进行是否包含与添加修改字段值的操作,依旧报错第一个。再次将两次Graphic生成做调整。
Graphic graphic = (from g in listGraphic where graphic.Attributes["key"].ToString() == strCode select g).FirstOrDefault();
Graphic newGraphic = graphic;
newGraphic.Symbol = symbol;
customLayer.Graphics.Add(newGraphic);
此时,依旧报错第一个。
再次将两次Graphic生成做调整。
Graphic graphic = (from g in listGraphic where graphic.Attributes["key"].ToString() == strCode select g).FirstOrDefault();
Graphic newGraphic = new Graphic();
newGraphic.Symbol = symbol;
newGraphic.Geometry = graphic.Geometry;
customLayer.Graphics.Add(newGraphic);
至此,问题解决。但为何保证Graphic要素中的属性字段值不一致的绘制在不同图层依旧报错,如有懂得原理的请多指点。