现在的位置: 首页 > 综合 > 正文

扩展 DataGridView 的功能(五)

2012年09月30日 ⁄ 综合 ⁄ 共 2091字 ⁄ 字号 评论关闭

文章最后有代码下载

 

DataGridView 的功能还是很强大的,每个cell都可以设置单独的style,可以打造出非常漂亮的效果。

 

但是如何让同一个 cell 里的文字设置不同的 style 呢, 比如像下图这样

 

 

有了前面的基础,相信扩展这个功能还是比较简单的, 总体来说就是重写 Cell 的 Paint 方法,想怎么画就怎么画

 

但是如何表示这种富文本的结构呢?想了一会,还是觉得用 html 标签来表示就行了。

上图中得文本用 html 标签来表示就变成了

string text = "<font color=\"red\" name=\"楷体\" size=\"14\">少年</font><font color=\"blue\" name=\"微软雅黑\" size=\"16\">张</font>三丰";

然后写一个简单的 html parser 解析它就行了。

主要代码如下 

void PaintText(Graphics g, Rectangle rect, string text, bool selected, DataGridViewCellStyle cell_style)
        {
            Document = parser.parse_text(text);
            Point pt = rect.Location;
            foreach (var node in Document.Nodes)
            {
                Font font = get_node_font(node, cell_style);
                Color clr = get_node_color(node, selected, cell_style);
                Size size = TextRenderer.MeasureText(node.InnerText, font);
                pt.Y = rect.Top + (rect.Height - size.Height) / 2;
                using (Brush bru = new SolidBrush(clr))
                {
                    g.DrawString(node.InnerText, font, bru, pt);
                }
                pt.X += size.Width;
            }
        }

        Font get_node_font(DOMNode node, DataGridViewCellStyle cell_style)
        {
            Font font = cell_style.Font;
            if (node.Name == "font" && node.Attributes.ContainsKey("name") && node.Attributes.ContainsKey("size"))
            {
                float font_size = cell_style.Font.Size;
                float.TryParse(node.Attributes["size"], out font_size);
                font = new Font(node.Attributes["name"], font_size);
            }
            return font;
        }

        Color get_node_color(DOMNode node, bool selected, DataGridViewCellStyle cell_style)
        {
            Color clr = selected ? cell_style.SelectionForeColor : cell_style.ForeColor;
            if (node.Name == "font" && node.Attributes.ContainsKey("color"))
            {
                clr = ColorTranslator.FromHtml(node.Attributes["color"]);
                if (selected)
                    clr = Color.FromArgb(~(clr.ToArgb()&0x00FFFFFF));
            }
            return clr;

        } 

代码下载 

抱歉!评论已关闭.