You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过onFieldChanged事件实现Azure DevOps字段值复制?

当然可以实现!你想要的当System.State变为todo时自动把System.Title同步到System.Description的需求,完全可以通过Azure DevOps扩展的onFieldChanged事件来完成。我来给你一步步拆解实现方法:

核心实现思路

  • 先注册监听工作项表单的字段变更事件,重点盯紧System.State字段的变化
  • 当检测到System.State被改成todo时,立刻获取当前System.Title的内容
  • 把获取到的标题内容赋值给System.Description字段

具体代码实现

1. 配置vss-extension.json

首先要确保你的扩展清单正确声明了对工作项表单的贡献,示例配置如下:

{
  "manifestVersion": 1,
  "id": "workitem-field-sync-extension",
  "name": "Work Item Field Sync Tool",
  "version": "1.0.0",
  "publisher": "your-publisher-id", // 替换成你的发布者ID
  "targets": [{"id": "Microsoft.VisualStudio.Services"}],
  "contributions": [
    {
      "id": "workitem-form-sync",
      "type": "ms.vss-work-web.workitem-form-group",
      "targets": ["ms.vss-work-web.workitem-form"],
      "properties": {
        "name": "Field Sync",
        "uri": "workitem-form.html"
      }
    }
  ],
  "files": [
    {"path": "workitem-form.html", "addressable": true},
    {"path": "scripts", "addressable": true},
    {"path": "node_modules/vss-web-extension-sdk/lib", "addressable": true, "packagePath": "lib"}
  ]
}

2. 编写HTML页面(workitem-form.html)

这个页面主要用来加载Azure DevOps的SDK和你的业务脚本:

<!DOCTYPE html>
<html>
<head>
    <script src="lib/VSS.SDK.min.js"></script>
</head>
<body>
    <script src="scripts/sync-fields.js"></script>
</body>
</html>

3. 核心逻辑脚本(scripts/sync-fields.js)

这部分是实现字段同步的关键,通过SDK注册字段变更事件并处理逻辑:

VSS.init({
    explicitNotifyLoaded: true,
    usePlatformStyles: true
});

VSS.require(["TFS/WorkItemTracking/Services"], function (WorkItemServices) {
    // 获取工作项表单服务实例
    WorkItemServices.WorkItemFormService.getService().then(function (formService) {
        // 注册字段变更通知
        formService.registerFieldChangedNotification(function (fieldName, oldValue, newValue) {
            // 只处理System.State字段变更,且新值是todo的情况
            if (fieldName === "System.State" && newValue.toLowerCase() === "todo") {
                // 获取System.Title的当前值
                formService.getFieldValue("System.Title").then(function (titleContent) {
                    // 将标题内容赋值给System.Description
                    formService.setFieldValue("System.Description", titleContent);
                });
            }
        });
    });

    // 通知SDK加载完成
    VSS.notifyLoadSucceeded();
});

一些注意事项

  • 权限问题:发布扩展时,要确保勾选了工作项相关的权限(比如“读取和写入工作项”),否则扩展无法操作字段值
  • 状态值匹配:有些项目里的状态可能是To Do(首字母大写)或者其他变体,记得调整代码里的判断条件,比如用newValue.toLowerCase() === "todo"来兼容大小写
  • 覆盖逻辑:如果System.Description已经有内容,当前代码会直接覆盖,你可以根据需求添加判断,比如只在Description为空时才同步
  • 调试方式:开发阶段可以用Azure DevOps的“加载已解压缩的扩展”功能,本地加载扩展进行测试,方便快速调整代码

内容的提问来源于stack exchange,提问作者Jay K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:22:49