sdk
latest
false
重要 :
请注意,此内容已使用机器翻译进行了部分本地化。 新发布内容的本地化可能需要 1-2 周的时间才能完成。
UiPath logo, featuring letters U and I in white

开发者指南

上次更新日期 2025年10月30日

Writing the code for a custom activity

为了更好地理解如何为自定义活动编写代码,我们将创建一个简单的活动,它要求用户输入两个数字,然后输出两个数字之和的平方。
  1. 启动 Microsoft Visual Studio。
  2. Select File > New >Project… (shortcut: Ctrl + Shift + N). The New Project window is displayed.
  3. 从“ 语言” 下拉菜单中选择“ C# ”。 系统将显示使用 C# 的所有依赖项的列表。
  4. Select Class Library (.NET Framework). This helps us export the custom activity as a .dll file. Select Next to go to the Configure your new project window.


  5. Fill in the Project name field with the desired activity name. In our case, we can use "MathSquareOfSum".
  6. 从“ 框架 ”下拉菜单中选择“ .NET Framework 4.6.1 ”。 这可确保该库与 UiPath Studio 兼容。
    注意: 在 Windows - 旧版项目中,UiPath Studio 支持使用 .NET Framework 4.5.2 至 4.6.1 创建的活动。 有关如何将活动迁移到 .NET 以在具有 Windows 兼容性的项目中使用的信息,请参阅将 活动迁移到 .NET 6


  7. Select Create to go to the code designer and start writing the activity code.
  8. 在“ 解决方案资源管理器 ”面板中,右键单击“ 引用 ”分支,然后选择“ 添加引用…”。 系统将显示“ 引用管理器 ”窗口。
  9. 搜索 System.ActivitiesSystem.ComponentModel.Composition 引用并添加它们。 请务必选中每个选项前面的复选框,然后单击“ 确定”。 这样做使我们能够使用上述参考中的类。




  10. 现在,我们需要确保代码使用新添加的引用。 这可以通过在代码设计器中添加以下行来完成:
    using System.Activities;
    using System.ComponentModel;using System.Activities;
    using System.ComponentModel;
    我们的项目现在应如下所示:


  11. 添加输入和输出参数。 在本例中,代码应如下所示:
    //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
     
    //Dots allow for hierarchy. App Integration.Excel is where Excel activities are.
    [Category("Category.Where.Your.Activity.Appears.In.Toolbox")]
    [DisplayName("Human readable name instead of class name")]
    [Description("The text of the tooltip")]
     public class MathSqSum : CodeActivity
    {
     
        //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
                 [Category("Input")]
            [DisplayName("First Number")]
            [Description("Enter the first number")]
            [RequiredArgument]
            public InArgument<int> FirstNumber { get; set; }
            [Category("Input")]
            [DisplayName("Second Number")]
            [Description("Enter the second number")]
            [RequiredArgument]
            public InArgument<int> SecondNumber { get; set; }
            [Category("Output")]
            public OutArgument<int> ResultNumber { get; set; }
            protected override void Execute(CodeActivityContext context)
            {
            }//Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
     
    //Dots allow for hierarchy. App Integration.Excel is where Excel activities are.
    [Category("Category.Where.Your.Activity.Appears.In.Toolbox")]
    [DisplayName("Human readable name instead of class name")]
    [Description("The text of the tooltip")]
     public class MathSqSum : CodeActivity
    {
     
        //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
                 [Category("Input")]
            [DisplayName("First Number")]
            [Description("Enter the first number")]
            [RequiredArgument]
            public InArgument<int> FirstNumber { get; set; }
            [Category("Input")]
            [DisplayName("Second Number")]
            [Description("Enter the second number")]
            [RequiredArgument]
            public InArgument<int> SecondNumber { get; set; }
            [Category("Output")]
            public OutArgument<int> ResultNumber { get; set; }
            protected override void Execute(CodeActivityContext context)
            {
            }
    <DisplayName(" ")> 属性是 Studio 中“ 属性 ”面板中输入字段之前显示的标签。 <Description(" ")> 属性是鼠标悬停时显示的工具提示文本。


    The <ReguiredArgument> attribute is needed if you want a declared element to be mandatory for input. If it is not filled in, a caution icon appears in the title bar of the activity.
  12. Add the functionality in the <Execute( )> overridden function. In our case, it looks like this:
    protected override void Execute(CodeActivityContext context)
    {
        var firstNumber = FirstNumber.Get(context);
      var secondNumber = SecondNumber.Get(context);
      
      var result = (int)Math.Pow(firstNumber + secondNumber, 2);
      ResultNumber.Set(context, result);
    }protected override void Execute(CodeActivityContext context)
    {
        var firstNumber = FirstNumber.Get(context);
      var secondNumber = SecondNumber.Get(context);
      
      var result = (int)Math.Pow(firstNumber + secondNumber, 2);
      ResultNumber.Set(context, result);
    }

(Optional) Building a Designer Interface

如果您不希望活动具有设计器界面,则可以跳至构建库部分。

重要提示:

为了构建设计器界面,您需要在 Visual Studio 中安装 Windows 工作流基础 组件。 如果尚未从 Visual Studio 安装程序中选择组件,则可以按如下方式添加:

  • 在 Visual Studio 中,单击“ 工具 ” 菜单,然后选择 “获取工具和功能…”。 系统将显示“Visual Studio 安装程序”窗口。
  • 切换到“ 单个组件 ”选项卡,然后搜索 Windows Workflow Foundation 组件。 它位于“ 开发活动 ”部分下。
  • 选中 Windows Workflow Foundation 组件前面的复选框,然后单击“ 修改”。 所需组件已安装。


  1. Right-click the project from the Properties panel (in our case, the project is MathSquareOfSum). The context menu shows up.
  2. From the Add item, select New Item.... The Add New Item window is displayed.
  3. Select Workflow under the Installed category on the left panel. All related elements are displayed.
  4. Select Activity Designer and click Add to include the item in the project.


    系统随即会添加“ 活动设计器 ”项目,并会立即打开相应的 .xaml 文件。 它应该如下所示:


  5. Replace the existing Activity Designer code with the following:
    <sap:ActivityDesigner x:Class="MathSquareOfSum.MathSqSumDesigner"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
        xmlns:sapc="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation"
        xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">
        <a href="sap:ActivityDesigner.Resources">sap:ActivityDesigner.Resources</a>
            <ResourceDictionary>
                <sapc:ArgumentToExpressionConverter x:Key="ArgumentToExpressionConverter" />
            </ResourceDictionary>
        </sap:ActivityDesigner.Resources>
        <DockPanel Width="300">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                    <ColumnDefinition Width="210"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="0" Grid.Column="0" Text="First Number"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="0" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter first number" Expression="{Binding Path=ModelItem.FirstNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
                <TextBlock Grid.Row="1" Grid.Column="0" Text="Second Number"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="1" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter second number" Expression="{Binding Path=ModelItem.SecondNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
                <TextBlock Grid.Row="2" Grid.Column="0" Text="Result"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="2" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="The sum of the numbers" UseLocationExpression="True" Expression="{Binding Path=ModelItem.ResultNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=Out, Mode=TwoWay}" />
            </Grid>
        </DockPanel>
    </sap:ActivityDesigner><sap:ActivityDesigner x:Class="MathSquareOfSum.MathSqSumDesigner"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
        xmlns:sapc="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation"
        xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">
        <a href="sap:ActivityDesigner.Resources">sap:ActivityDesigner.Resources</a>
            <ResourceDictionary>
                <sapc:ArgumentToExpressionConverter x:Key="ArgumentToExpressionConverter" />
            </ResourceDictionary>
        </sap:ActivityDesigner.Resources>
        <DockPanel Width="300">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                    <ColumnDefinition Width="210"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="0" Grid.Column="0" Text="First Number"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="0" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter first number" Expression="{Binding Path=ModelItem.FirstNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
                <TextBlock Grid.Row="1" Grid.Column="0" Text="Second Number"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="1" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter second number" Expression="{Binding Path=ModelItem.SecondNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
                <TextBlock Grid.Row="2" Grid.Column="0" Text="Result"></TextBlock>
                <sapv:ExpressionTextBox Grid.Row="2" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="The sum of the numbers" UseLocationExpression="True" Expression="{Binding Path=ModelItem.ResultNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=Out, Mode=TwoWay}" />
            </Grid>
        </DockPanel>
    </sap:ActivityDesigner>
    新定义的活动布局现在应如下所示:


  6. Right-click the activity (in our case ActMathSquareOfSum), and from the Add menu, select Class.... The Add New Item window is displayed.
  7. The Class item is already selected. All that is needed now is to rename it to DesignerMetadata.cs, and select Add. The new class is now added to the activity and opens up in a new tab.


  8. Add the following content in the newly-created DesignerMetadata class:
    using MathSquareOfSum;
    using System.Activities.Presentation.Metadata;
    using System.ComponentModel;
    namespace ActMathSquareOfSum
    {
        public class DesignerMetadata : IRegisterMetadata
        {
            public void Register()
            {
                AttributeTableBuilder attributeTableBuilder = new AttributeTableBuilder();
                attributeTableBuilder.AddCustomAttributes(typeof(MathSqSum), new DesignerAttribute(typeof(MathSqSumDesigner)));
                MetadataStore.AddAttributeTable(attributeTableBuilder.CreateTable());
            }
        }
    }using MathSquareOfSum;
    using System.Activities.Presentation.Metadata;
    using System.ComponentModel;
    namespace ActMathSquareOfSum
    {
        public class DesignerMetadata : IRegisterMetadata
        {
            public void Register()
            {
                AttributeTableBuilder attributeTableBuilder = new AttributeTableBuilder();
                attributeTableBuilder.AddCustomAttributes(typeof(MathSqSum), new DesignerAttribute(typeof(MathSqSumDesigner)));
                MetadataStore.AddAttributeTable(attributeTableBuilder.CreateTable());
            }
        }
    }
  • (Optional) Building a Designer Interface

此页面有帮助吗?

获取您需要的帮助
了解 RPA - 自动化课程
UiPath Community 论坛
Uipath Logo
信任与安全
© 2005-2025 UiPath。保留所有权利。