zoukankan      html  css  js  c++  java
  • 扩展 DataGridView 的功能(五)

    文章最后有代码下载

    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;

            } 


    代码下载 

  • 相关阅读:
    Windows 10 Universal App 开发记录
    Windows Phone 8.1 开发会用到的方法
    Android Activity设置全屏
    Android视频录制命令screenrecord
    Android ScrollView中嵌套ListView只显示一行的解决办法
    Android 4.4.4: java.lang.SecurityException: Package com.android.settings does not belong to 1001
    自定义Android spinner样式并添加监听事件
    GSON快速实现内部类
    android的Banner轮播图框架
    Okhttp与Okhttputils的用法及区别
  • 原文地址:https://www.cnblogs.com/michaelhuwei/p/2662480.html
Copyright © 2011-2022 走看看