// when layers are added/removed private void Layers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { LayerCollection layers = (LayerCollection)sender; // Put updating of measurable layers in a throttle timer, meaning that this logic will // only be invoked once if the CollectionChanged event fires multiple times within two // tenths of a second. This is necessary because changing to a basemap in a different // spatial reference results in clearing and rebuilding the layers collection. if (_updateMeasurableLayersThrottler == null) { _updateMeasurableLayersThrottler = new ThrottleTimer(20, () => { // Check whether all layers are initialized if (layers.Any(l => !l.IsInitialized)) { layers.LayersInitialized += Layers_LayersInitialized; // Wait for initialization } else { UpdateMeasurableLayers(); // Update measurable layers collection now } }); } _updateMeasurableLayersThrottler.Invoke(); // Check whether layers were added if (e.NewItems != null) { // Hook into visibility changed events for added layers foreach (Layer layer in e.NewItems) { layer.PropertyChanged += Layer_PropertyChanged; if (layer is ArcGISDynamicMapServiceLayer) { ISublayerVisibilitySupport subLayerSupport = layer as ISublayerVisibilitySupport; subLayerSupport.VisibilityChanged += SubLayerSupport_VisibilityChanged; } } } // Check whether layers were removed if (e.OldItems != null) { // Unhook from visibility changed events for removed layers foreach (Layer layer in e.OldItems) { layer.PropertyChanged -= Layer_PropertyChanged; if (layer is ArcGISDynamicMapServiceLayer) { ISublayerVisibilitySupport subLayerSupport = layer as ISublayerVisibilitySupport; subLayerSupport.VisibilityChanged -= SubLayerSupport_VisibilityChanged; } } } // If draw layer has been added to the map, check whether it is the top-most if (layers.Contains(DrawLayer) && layers.IndexOf(DrawLayer) != layers.Count - 1) { // Draw layer is not top-most. Move it to the top by removing and re-adding it. Wrap in // a begin invoke call so the collection is modified outside the CollectionChanged event. Map.Dispatcher.BeginInvoke(() => { layers.Remove(DrawLayer); layers.Add(DrawLayer); }); } }