如何在SourceGrid中优雅自定义绘制单元格?现有实现存痛点
优化SourceGrid自定义单元格的优雅实现方案
针对你目前使用SourceGrid时,填充数据需要双重类型转换的不优雅问题,推荐通过自定义Cell类封装内部视图和元素的方式来解决,既符合SourceGrid的设计规范,又能简化外部调用逻辑。
核心改进思路
将自定义的MyCustomCellElement和SourceGrid.Cells.Views.Cell封装到一个自定义Cell类中,对外直接暴露MyCustomData属性,避免外部代码进行多层类型转换。
完整实现代码
1. 自定义Cell类
public class MyCustomCell : SourceGrid.Cells.Cell { // 直接持有自定义元素的引用,避免类型转换 private readonly MyCustomCellElement _customElement; public MyCustomCell(string value) : base(value) { // 初始化视图和自定义元素 var view = new SourceGrid.Cells.Views.Cell(); _customElement = new MyCustomCellElement(); view.ElementText = _customElement; View = view; } // 对外暴露自定义数据属性,直接映射到内部元素 public MyObject MyCustomData { get => _customElement.MyCustomData; set => _customElement.MyCustomData = value; } }
2. 自定义Cell元素(保留原有绘制逻辑)
class MyCustomCellElement : DevAge.Drawing.VisualElements.TextGDI { public MyObject MyCustomData { get; set; } protected override void OnDraw(GraphicsCache graphics, RectangleF area) { if (Value == null || Value.Length == 0) return; var brush = Enabled ? graphics.BrushsCache.GetBrush(ForeColor) : graphics.BrushsCache.GetBrush(Color.FromKnownColor(KnownColor.GrayText)); // 这里可以根据MyCustomData调整绘制逻辑,比如改变颜色、添加图标等 graphics.Graphics.DrawString(Value, Font, brush, area, StringFormat); } }
3. 创建单元格的代码
// 直接实例化自定义Cell,无需手动配置View和Element Cell c = new MyCustomCell(Value);
4. 填充数据的代码
// 仅需一次类型转换(如果Grid未泛型化),或直接访问属性 ((MyCustomCell)Grid[row][col]).MyCustomData = MyCustomObj; // 如果提前知道单元格类型,可简化为: // MyCustomCell customCell = (MyCustomCell)Grid[row][col]; // customCell.MyCustomData = MyCustomObj;
方案优势
- 封装性更强:内部视图和元素的细节被隐藏,外部代码只需关注自定义Cell的属性
- 避免类型转换耦合:不再依赖多层
as转换,减少运行时类型错误风险 - 扩展性更好:后续若需添加其他自定义属性或逻辑,只需在
MyCustomCell类中扩展,无需修改外部调用代码
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

