How can I programatically set a label expression for a specified layer on my map?

1578
2
Jump to solution
04-11-2019 11:46 AM
KhamilleJaynes
New Contributor III

Hello,

I am working with ArcGIS Pro SDK to build a configuration. I currently have a checkbox control on my ribbon. When I check the box, my labels turn on for the feature class I specify. I was able to figure this out using this code snippet from the Pro SDK GitHub. 

Is there a way that I could set the label expression programatically, instead of having to select the layer from my Contents pane and changing it manually under the labeling ribbon tab? 

I've tried using AddLabelClass() on my feature layer but it doesn't produce the result I want if I put my field name in the parameter. 

Thank you!

1 Solution

Accepted Solutions
UmaHarano
Esri Regular Contributor

Hi

You can modify any layer's label expression using this snippet:

Modify label expression using Arcade

var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPolygon);
if (lyr == null) return;
QueuedTask.Run(() => {
    //Get the layer's definition
    //community sample Data\Admin\AdminSample.aprx
    var lyrDefn = lyr.GetDefinition() as CIMFeatureLayer;
    if (lyrDefn == null) return;
    //Get the label classes - we need the first one
    var listLabelClasses = lyrDefn.LabelClasses.ToList();
    var theLabelClass = listLabelClasses.FirstOrDefault();
    //set the label class Expression to use the Arcade expression
    theLabelClass.Expression = "return $feature.STATE_NAME + TextFormatting.NewLine + $feature.POP2000;";
    //Set the label definition back to the layer.
    lyr.SetDefinition(lyrDefn);
});

Thanks

Uma

View solution in original post

2 Replies
UmaHarano
Esri Regular Contributor

Hi

You can modify any layer's label expression using this snippet:

Modify label expression using Arcade

var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPolygon);
if (lyr == null) return;
QueuedTask.Run(() => {
    //Get the layer's definition
    //community sample Data\Admin\AdminSample.aprx
    var lyrDefn = lyr.GetDefinition() as CIMFeatureLayer;
    if (lyrDefn == null) return;
    //Get the label classes - we need the first one
    var listLabelClasses = lyrDefn.LabelClasses.ToList();
    var theLabelClass = listLabelClasses.FirstOrDefault();
    //set the label class Expression to use the Arcade expression
    theLabelClass.Expression = "return $feature.STATE_NAME + TextFormatting.NewLine + $feature.POP2000;";
    //Set the label definition back to the layer.
    lyr.SetDefinition(lyrDefn);
});

Thanks

Uma

KhamilleJaynes
New Contributor III

Hi, this was very helpful and worked with my program. Thank you!

0 Kudos