如果属性值需要依赖公式的计算结果动态变化,可以通过标注FormulaPropertyAttribute 的方式设置。
注意,标注FormulaPropertyAttribute的属性类型必须是 object。
public class MyPluginCellType : CellType { [FormulaProperty] public object MyProperty { get; set; } }
在设计器中效果如下:
为支持公式属性,单元格对应的JavaScript类也需要对应的处理,可以通过evaluateFormula方法计算公式的值。
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase { content = null; createContent() { this.content = $("<div style='width:100%;height:100%;'></div>"); return this.content; } onPageLoaded() { const prop = this.CellElement.CellType.MyProperty; const result = this.evaluateFormula(prop) this.content.text(result) } } Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);
相信看了以上示例代码之后一定会有小伙伴有所疑惑,为什么不在createContent函数里计算公式的值,而是在onPageLoaded函数中呢?
因为createContent函数是用来构建当前单元格的,页面上的每一个单元格都会一个一个的调用一个方法来构建,如果在createContent函数中计算公式值,如公式又刚好依赖了还没有被构建好的单元格,会导致计算结果不正确。解决方案就是吧计算逻辑延后到 onPageLoaded 函数中。这个函数会在所有单元格被构建完成后调用。
另外,我们注意到,使用了上述的JavaScript代码,单元格属性的初始值经过了计算,但是如果依赖单元格的值发生了变化,不会重新计算公式属性值。为了解决这个问题,需要监听onDependenceCellValueChanged回调函数,这个回调函数会自动分析当前单元格依赖的其他单元格,当依赖的单元格值发生变化时会触发这个回调。所以JavaScript代码的改进版如下:
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase { content = null; createContent() { this.content = $("<div style='width:100%;height:100%;'></div>"); return this.content; } onPageLoaded() { const calcFormulaProps = () => { const prop = this.CellElement.CellType.MyProperty; const result = this.evaluateFormula(prop) this.content.text(result) } calcFormulaProps(); this.onDependenceCellValueChanged(() => { calcFormulaProps(); }) } } Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);
如果需要更细致的控制,可以通过FormulaPropertyAttribute的其他属性来控制。
1.提供备选列表
- 设置FormulaPropertyAttribute 的 RecommendedValues 属性。
使用“|”分隔多个候选项。 代码:
public class MyPluginCellType : CellType { [FormulaProperty(RecommendedValues = "学生|教师|工人")] public object MyProperty { get; set; } }
- 效果:
- 设置FormulaPropertyAttribute 的 RecommendedValues 属性。
2.支持输入多行文本。
- 设置FormulaPropertyAttribute 的 AcceptsReturn 属性。
代码:
public class MyPluginCellType : CellType { [FormulaProperty(AcceptsReturn = true)] public object MyProperty { get; set; } }
- 效果: