Skip to content

枚举类型属性

如果属性的类型是枚举,那么在设计器中会以下拉列表的形式提供给用户编辑

csharp
    public class MyPluginCellType : CellType
    {
        public UserType MyProperty1 { get; set; }
    }
    public enum UserType
    {
        Student,
        Teacher,
        Worker
    }

在设计器中效果如下

1669455815243-91aa2248-b855-4533-ad33-8869ece9b3a1.png

需要注意的是,在C#代码中的枚举生成到JavaScript 中实际上是一个整数,默认情况下整数的值就是枚举出现的顺序

1669455978688-a8c78c90-690f-4461-9074-f36f35c58ff6.png

所以在JavaScript代码中需要如下处理

javascript
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase {
    createContent() {
        const propValue = this.CellElement.CellType.MyProperty;
        let text = "";
        switch (propValue) {
            case 0:
                text = "学生"
                break;
            case 1:
                text = "教师"
                break;
            case 2:
                text = "工人"
                break;
            default:
        }
        return $("<div>" + text + "<div>");
    }
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);

为了提升代码的可读性性,可以替换为一下等价代码处理枚举类型属性

javascript
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase {
    userType = {
        0: "学生",
        1: "教师",
        2: "工人",
    }
    createContent() {
        const propValue = this.CellElement.CellType.MyProperty;
        const text = this.userType[propValue];
        return $("<div>" + text + "<div>");
    }
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);

自定义枚举项目显示名称, 可以通过标注 Description 实现

csharp
    public class MyPluginCellType : CellType
    {
        public UserType MyProperty1 { get; set; }
    }
    public enum UserType
    {
        [Description("学生")]
        Student,
        [Description("教师")]
        Teacher,
        [Description("工人")]
        Worker
    }

效果
1670298604968-ad5ac366-af39-45bd-84f1-a9e989d818fc.png

更新: 2022-12-06 11:50:22
原文: https://www.yuque.com/robert-bh51n/ea8l6c/lf4dpv8pol8dgblu