欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

DevExpress13.2.9 控件使用经验总结

程序员文章站 2022-04-10 15:36:47
一.换肤功能 1. 添加 DevExpress.OfficeSkins 和 DevExpress.BonusSkins 两个引用 2. 皮肤注册 DevExpress.UserSkins.BonusSkins.Register(); DevExpress.Skins.SkinManager.Enab ......

一.换肤功能

  1. 添加 DevExpress.OfficeSkins 和 DevExpress.BonusSkins 两个引用

  2. 皮肤注册

DevExpress13.2.9 控件使用经验总结
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
View Code

  3. 加载皮肤列表,调用 SkinTools.LoadSkinList 函数

DevExpress13.2.9 控件使用经验总结
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using psi.Common;
using psi.Interfaces;
using DevExpress.Skins;
using DevExpress.LookAndFeel;

/************************************************************************* 
 * 程序说明: 设置皮肤工具
 **************************************************************************/
namespace psi.Library
{
    /// <summary>
    /// 设置皮肤工具
    /// </summary>
    public class SkinTools
    {
        private static ToolStripMenuItem _CurrentSkinList = null;

        /// <summary>
        /// 加载皮肤列表
        /// </summary>
        public static void LoadSkinList(ToolStripMenuItem owner)
        {
            _CurrentSkinList = owner;

            int skinCount = DevExpress.Skins.SkinManager.Default.Skins.Count;
            ToolStripItem[] itemArr = new ToolStripItem[skinCount];
            int index = 0;
            foreach (DevExpress.Skins.SkinContainer skin in DevExpress.Skins.SkinManager.Default.Skins)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = skin.SkinName;
                item.Name = skin.SkinName;
                item.Checked = skin.SkinName == SystemConfig.CurrentConfig.SkinName;
                item.Click += new System.EventHandler(OnSetSkinClick);
                itemArr[index] = item;
                ++index;
            }

            owner.DropDownItems.AddRange(itemArr);
        }

        /// <summary>
        /// 设置皮肤
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnSetSkinClick(object sender, EventArgs e)
        {
            ToolStripMenuItem clickItem = sender as ToolStripMenuItem;
            SetSkin(clickItem.Name);

            if (_CurrentSkinList != null)
            {
                foreach (ToolStripMenuItem item in _CurrentSkinList.DropDownItems)
                {
                    item.Checked = false;
                }
            }

            clickItem.Checked = true;
        }

        public static void SetSkin(string skinName)
        {
            //设置所有窗体的皮肤
            for (int i = 0; i < Application.OpenForms.Count - 1; i++)
            {
                Form form = Application.OpenForms[i];

                if (form is IFormBase) (form as IFormBase).SetSkin(skinName);
            }
        }
    }
}
View Code

  4. 效果如下图

DevExpress13.2.9 控件使用经验总结

 

二. Grid 显示行号以及设置行号列名称

  1. 添加 GridView 方法 CustomDrawRowIndicator

DevExpress13.2.9 控件使用经验总结
/// <summary>
/// 显示行号和设置行号列头部的字符
/// </summary>
private void gvSummary_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
    if (e.Info.Kind == DevExpress.Utils.Drawing.IndicatorKind.Header)
    {
        e.Info.DisplayText = "行号";
    }
    e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
    if (e.Info.IsRowIndicator && e.RowHandle >= 0)
    {
        e.Info.DisplayText = Convert.ToString(e.RowHandle + 1);
    }
}
View Code

  2. 效果如下图

DevExpress13.2.9 控件使用经验总结

 

三. Grid 下添加固定合计行

  1. 继承 GridView ,自定义表格 GridViewSummary,改变Grid父级控制器

DevExpress13.2.9 控件使用经验总结
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using System.Drawing;
using DevExpress.XtraGrid;
using System.Collections;

namespace psi.UserControls.SummaryDataGrid
{
    public partial class GridViewSummary : GridView
    {
        #region Browsable properties

        /// <summary>
        /// 是否显示合计行的头部
        /// </summary>
        private bool displaySumRowHeader;
        [Browsable(true), Category("Summary")]
        public bool DisplaySumRowHeader
        {
            get { return displaySumRowHeader; }
            set { displaySumRowHeader = value; }
        }

        /// <summary>
        /// 合计行头部文本
        /// </summary>
        private string sumRowHeaderText;
        [Browsable(true), Category("Summary")]
        public string SumRowHeaderText
        {
            get { return sumRowHeaderText; }
            set { sumRowHeaderText = value; }
        }

        /// <summary>
        /// 合计行头部是否加粗
        /// </summary>
        private bool sumRowHeaderTextBold;
        [Browsable(true), Category("Summary")]
        public bool SumRowHeaderTextBold
        {
            get { return sumRowHeaderTextBold; }
            set { sumRowHeaderTextBold = value; }
        }

        /// <summary>
        /// 需要合计列的列名数组
        /// </summary>
        private string[] summaryColumns;
        [Browsable(true), Category("Summary")]
        public string[] SummaryColumns
        {
            get { return summaryColumns; }
            set { summaryColumns = value; }
        }

        /// <summary>
        /// 合并的列的集合
        /// </summary>
        private List<MergeColumn> mergeColumns = new List<MergeColumn>();
        [Browsable(true), Category("Summary")]
        [TypeConverter(typeof(System.ComponentModel.CollectionConverter))]       
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<MergeColumn> MergeColumns
        {
            get { return mergeColumns; }
        }
        #endregion

        #region Declare variables

        private SummaryControlContainer summaryControl;
        private Panel parentPanel;

        public SummaryControlContainer SummaryControl
        {
            get{return this.summaryControl;}
        }
        #endregion

        #region Constructor

        public GridViewSummary()
        {
            InitializeComponent();

            this.parentPanel = new Panel();
            summaryControl = new SummaryControlContainer(this);
        }

        #endregion

        /// <summary>
        /// 改变合计列的皮肤样式,使适应DevExpress的皮肤
        /// </summary>
        private void ChangeSummarySkin()
        {
            if (!DesignMode && this.summaryControl != null)
            {
                //Skin CommonSkin = CommonSkins.GetSkin(UserLookAndFeel.Default.ActiveLookAndFeel);
                Skin GridSkin = GridSkins.GetSkin(UserLookAndFeel.Default.ActiveLookAndFeel);
                this.summaryControl.BackColor = GridSkin[GridSkins.SkinGridEvenRow].Color.BackColor;
            }
        }

        /// <summary>
        /// 改变Grid所属的父级控件
        /// </summary>
        private void ChangeParent()
        {
            Control parent = this.GridControl.Parent;
            if (!DesignMode && parent != null)
            {
                gridOldWidth = GridControl.Width;

                summaryControl.InitialHeight = this.RowHeight + 2;
                summaryControl.ForeColor = Color.Transparent;
                summaryControl.Height = summaryControl.InitialHeight;

                this.parentPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                this.parentPanel.Dock = DockStyle.Top;
                Size panelSize = new Size();
                panelSize.Height = this.GridControl.Height + summaryControl.InitialHeight;
                this.parentPanel.Size = panelSize;

                summaryControl.Dock = DockStyle.Bottom;

                int controlIdx = parent.Controls.GetChildIndex(this.GridControl);
                parent.Controls.Remove(this.GridControl);

                this.GridControl.Location = new Point(0, 0);
                this.GridControl.SizeChanged += delegate(object sender, EventArgs e)
                {
                    GridControl obj = (GridControl)sender;
                    if (obj.Width != gridOldWidth)
                    {
                        AdjustColumnWidth();
                        summaryControl.resizeSumBoxes();
                        gridOldWidth = obj.Width;
                    }
                };

                this.parentPanel.Controls.Add(this.GridControl);
                this.parentPanel.Controls.Add(summaryControl);
                this.parentPanel.SizeChanged += delegate(object sender, EventArgs e)
                {
                    if (Program.HomeForm.WindowState != FormWindowState.Minimized)
                    {
                        Panel obj = (Panel)sender;
                        if (obj.Width != 0 && obj.Width != GridControl.Width)
                        {
                            gridOldWidth = GridControl.Width;
                            GridControl.Width = obj.Width;
                        }
                    }
                };
                parent.Controls.Add(parentPanel);
                parent.Controls.SetChildIndex(parentPanel, controlIdx);
            }
        }

        /// <summary>
        /// 取得所有显示的列
        /// </summary>
        public List<GridColumn> DisaplyColumns
        {
            get
            {
                List<GridColumn> result = new List<GridColumn>();
                GridColumnCollection columns = this.Columns;
                if (columns == null)
                    return result;
                foreach (GridColumn column in columns)
                {
                    if (column.Visible)
                        result.Add(column);
                }

                return result;
            }
        }

        public delegate void BeforeEndInitHandler();
        public event BeforeEndInitHandler BeforeEndInit;   

        public override void EndInit()
        {
            if (BeforeEndInit != null) BeforeEndInit();
            ChangeSummarySkin();
            ChangeParent();
            summaryControl.reCreateSumBoxes();
        }

        protected override void OnLookAndFeelChanged()
        {
            base.OnLookAndFeelChanged();

            ChangeSummarySkin();
            summaryControl.reCreateSumBoxes();
        }

        private int gridOldWidth;

        /// 手动处理列宽度
        public delegate void HandlerColumnWidth(GridColumn column, int maxWidth);
        public event HandlerColumnWidth ColumnWidthHandler;

        /// 不进行宽度调整的列
        public delegate List<GridColumn> ExcludeAdjustWidthColumns();
        public event ExcludeAdjustWidthColumns ExcludeAdjustColumns;

        /// <summary>
        /// 调整列宽度
        /// </summary>
        public void AdjustColumnWidth()
        {
            Control parent = this.GridControl.Parent;
            if (!DesignMode && parent != null)
            {
                int gridWidth = this.GridControl.Width;
                int columnsWidth = this.IndicatorWidth + 18;
                int count = 0;
                foreach (GridColumn column in DisaplyColumns)
                {
                    if (ExcludeAdjustColumns != null)
                    {
                        List<GridColumn> excludeColumns = ExcludeAdjustColumns();
                        if (excludeColumns != null && excludeColumns.Contains(column))
                        {
                            continue;
                        }
                    }
                    count++;
                    column.Width = (column.Width * gridWidth) / gridOldWidth;
                    if (ColumnWidthHandler != null) ColumnWidthHandler(column, gridWidth - columnsWidth);

                    columnsWidth += column.Width;                 
                }
            }   
        }

        /// <summary>
        /// 删除全部行
        /// </summary>
        public void ClearRows()
        {
            bool _mutilSelected = this.OptionsSelection.MultiSelect;//获取当前是否可以多选
            if (!_mutilSelected)
                this.OptionsSelection.MultiSelect = true;
            this.SelectAll();
            this.DeleteSelectedRows();
            this.OptionsSelection.MultiSelect = _mutilSelected;//还原之前是否可以多选状态
        }
    }
}
View Code

  2. GridViewSummary 所属的父级控制器,创建合计行

DevExpress13.2.9 控件使用经验总结
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using DevExpress.XtraGrid;
using System.Drawing;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using System.Data;

namespace psi.UserControls.SummaryDataGrid
{
    public class SummaryControlContainer : UserControl
    {
        #region Declare variables
        private Hashtable sumBoxHash;
        private GridViewSummary gridViewSummary;
        private Label sumRowHeaderLabel;

        private int initialHeight;
        public int InitialHeight
        {
            get { return initialHeight; }
            set { initialHeight = value; }
        }

        public Hashtable SumBoxHash
        {
            get { return this.sumBoxHash; }
        }

        #endregion

        #region Constructors

        public SummaryControlContainer(GridViewSummary gridViewSummary)
        {
            if (gridViewSummary == null)
                throw new Exception("GridViewSummary is null!");

            this.gridViewSummary = gridViewSummary;
            sumBoxHash = new Hashtable();
            sumRowHeaderLabel = new Label();
        }

        #endregion

        #region Functions

        /// <summary>
        /// Checks if passed object is of type of integer
        /// </summary>
        /// <param name="o">object</param>
        /// <returns>true/ false</returns>
        protected bool IsInteger(object o)
        {
            if (o is Int64)
                return true;
            if (o is Int32)
                return true;
            if (o is Int16)
                return true;
            return false;
        }

        /// <summary>
        /// Checks if passed object is of type of decimal/ double
        /// </summary>
        /// <param name="o">object</param>
        /// <returns>true/ false</returns>
        protected bool IsDecimal(object o)
        {
            if (o is Decimal)
                return true;
            if (o is Single)
                return true;
            if (o is Double)
                return true;
            return false;
        }

        /// <summary>
        /// Create summary boxes for each Column of the DataGridView        
        /// </summary>
        public void reCreateSumBoxes()
        {
            ReadOnlyTextBox sumBox;
            Skin GridSkin = GridSkins.GetSkin(UserLookAndFeel.Default.ActiveLookAndFeel);
            Skin CommonSkin = CommonSkins.GetSkin(UserLookAndFeel.Default.ActiveLookAndFeel);
            
            foreach (Control control in sumBoxHash.Values)
            {
                this.Controls.Remove(control);
            }

            int iCnt = 0;

            List<GridColumn> gridColumns = this.gridViewSummary.DisaplyColumns;
            foreach (GridColumn gridColumn in gridColumns)
            {
                sumBox = new ReadOnlyTextBox();
                sumBox.Top = 0;
                sumBox.Height = this.initialHeight;
                sumBox.BorderColor = GridSkin[GridSkins.SkinGridLine].Color.BackColor;
                sumBox.Font = this.gridViewSummary.GridControl.Font;
                sumBox.ForeColor = this.gridViewSummary.GridControl.ForeColor;
                iCnt++;

                bool isMergeColumn = false;
                foreach (MergeColumn mergeColumn in this.gridViewSummary.MergeColumns)
                {
                    if (gridColumn.VisibleIndex >= mergeColumn.StartIndex && gridColumn.VisibleIndex <= mergeColumn.EndIndex)
                    {
                        isMergeColumn = true;
                        
                        if (gridColumn.VisibleIndex == mergeColumn.StartIndex)
                        {
                            if (gridColumns.Count == iCnt + (mergeColumn.EndIndex - mergeColumn.StartIndex + 1))
                            {
                                sumBox.IsLastColumn = true;
                            }
                            if (sumBoxHash.ContainsKey(mergeColumn.ColumnName))
                            {
                                ReadOnlyTextBox textBox = (ReadOnlyTextBox)sumBoxHash[mergeColumn.ColumnName];
                                sumBox.Text = textBox.Text;
                                sumBoxHash.Remove(mergeColumn.ColumnName);
                            }
                            sumBoxHash.Add(mergeColumn.ColumnName, sumBox);
                            this.Controls.Add(sumBox);
                        }
                        break;
                    }
                }
                if (isMergeColumn)
                    continue;


                if (gridColumns.Count == iCnt)
                    sumBox.IsLastColumn = true;

                if(sumBoxHash.ContainsKey(gridColumn.Name))
                {
                    ReadOnlyTextBox textBox = (ReadOnlyTextBox)sumBoxHash[gridColumn.Name];
                    sumBox.Text = textBox.Text;
                    sumBoxHash.Remove(gridColumn.Name);
                }
                sumBoxHash.Add(gridColumn.Name, sumBox);

                if (gridViewSummary.SummaryColumns != null && gridViewSummary.SummaryColumns.Length > 0)
                {
                    for (int iCntX = 0; iCntX < gridViewSummary.SummaryColumns.Length; iCntX++)
                    {
                        if (gridViewSummary.SummaryColumns[iCntX] == gridColumn.Name)
                        {
                            sumBox.TextAlign = TextHelper.TranslateGridColumnAligment(gridColumn.AppearanceCell.TextOptions.HAlignment);
                            sumBox.IsSummary = true;

                            sumBox.FormatString = gridColumn.DisplayFormat.FormatString;
                            if (gridColumn.ColumnType == typeof(System.Int32) || gridColumn.ColumnType == typeof(System.Int16) ||
                                gridColumn.ColumnType == typeof(System.Int64) || gridColumn.ColumnType == typeof(System.Single) ||
                                gridColumn.ColumnType == typeof(System.Double) || gridColumn.ColumnType == typeof(System.Single) ||
                                gridColumn.ColumnType == typeof(System.Decimal))
                                sumBox.Tag = System.Activator.CreateInstance(gridColumn.ColumnType);

                            break;
                        }
                    }
                }

                this.Controls.Add(sumBox);
            }

            if (gridViewSummary.DisplaySumRowHeader)
            {
                sumRowHeaderLabel.Width = this.gridViewSummary.IndicatorWidth;
                sumRowHeaderLabel.Font = new Font(this.gridViewSummary.GridControl.Font, this.gridViewSummary.SumRowHeaderTextBold ? FontStyle.Bold : FontStyle.Regular);
                sumRowHeaderLabel.Anchor = AnchorStyles.Left;
                sumRowHeaderLabel.TextAlign = ContentAlignment.MiddleCenter;
                sumRowHeaderLabel.Height = sumRowHeaderLabel.Font.Height;
                sumRowHeaderLabel.Top = Convert.ToInt32(Convert.ToDouble(this.InitialHeight - sumRowHeaderLabel.Height) / 2F);
                sumRowHeaderLabel.Text = gridViewSummary.SumRowHeaderText;

                sumRowHeaderLabel.ForeColor = this.gridViewSummary.GridControl.ForeColor;
                sumRowHeaderLabel.Margin = new Padding(0);
                sumRowHeaderLabel.Padding = new Padding(0);

                this.Controls.Add(sumRowHeaderLabel);
            }
            resizeSumBoxes();
        }

         /// <summary>
        /// Resize the text Boxes depending on the 
        /// width of the Columns of the GridView
        /// </summary>
        public void resizeSumBoxes()
        {
            this.SuspendLayout();
            if (sumBoxHash.Count > 0)
                try
                {
                    int rowHeaderWidth = gridViewSummary.OptionsView.ShowIndicator ? gridViewSummary.IndicatorWidth - 1: 0;
                    int curPos = rowHeaderWidth;

                    if (gridViewSummary.DisplaySumRowHeader && rowHeaderWidth > 0)
                    {
                        sumRowHeaderLabel.Dock = DockStyle.Left;
                    }
                    else
                    {
                        if (sumRowHeaderLabel.Visible)
                            sumRowHeaderLabel.Visible = false;
                    }

                    Rectangle oldBounds;
                    List<GridColumn> gridColumns = this.gridViewSummary.DisaplyColumns;
                    int mergeColumnWidth = 0;
                    foreach (GridColumn gridColumn in gridColumns)
                    {
                        ReadOnlyTextBox sumBox = null;

                        bool isMergeColumn = false;
                        foreach (MergeColumn mergeColumn in this.gridViewSummary.MergeColumns)
                        {
                            if (gridColumn.VisibleIndex >= mergeColumn.StartIndex && gridColumn.VisibleIndex <= mergeColumn.EndIndex)
                            {
                                isMergeColumn = true;
                                mergeColumnWidth += gridColumn.Width;
                                if (gridColumn.VisibleIndex == mergeColumn.EndIndex)
                                {
                                    sumBox = (ReadOnlyTextBox)sumBoxHash[mergeColumn.ColumnName];
                                    if (sumBox != null)
                                    {
                                        oldBounds = sumBox.Bounds;

                                        sumBox.SetBounds(curPos, 0, mergeColumnWidth, 0, BoundsSpecified.X | BoundsSpecified.Width);

                                        if (!sumBox.Visible)
                                            sumBox.Visible = true;

                                        if (oldBounds != sumBox.Bounds)
                                            sumBox.Invalidate();

                                        curPos += mergeColumnWidth;
                                        mergeColumnWidth = 0;
                                    }
                                }
                            }
                        }
                        if (isMergeColumn)
                            continue;

                        sumBox = (ReadOnlyTextBox)sumBoxHash[gridColumn.Name];
                        if (sumBox != null)
                        {
                            oldBounds = sumBox.Bounds;

                            sumBox.SetBounds(curPos, 0, gridColumn.Width, 0, BoundsSpecified.X | BoundsSpecified.Width);

                            if (!sumBox.Visible)
                                sumBox.Visible = true;

                            if (oldBounds != sumBox.Bounds)
                                sumBox.Invalidate();

                            curPos += gridColumn.Width;
                        }
                    }
                }
                finally
                {
                    this.ResumeLayout();
                }
        }
        #endregion
    }
}
View Code

  3. 合计行的单元格对象

DevExpress13.2.9 控件使用经验总结
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using psi.Common;

namespace psi.UserControls.SummaryDataGrid
{
    public partial class ReadOnlyTextBox : UserControl
    {

        StringFormat format;
        public event EventHandler TextChanged;

        public ReadOnlyTextBox()
        {
            InitializeComponent();

            format = new StringFormat(StringFormatFlags.NoWrap | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces);
            format.LineAlignment = StringAlignment.Center;

            this.Height = 10;
            this.Width = 10;

            this.Padding = new Padding(2);
        }

        private Color borderColor = Color.Black;

        private bool isSummary;
        public bool IsSummary
        {
            get { return isSummary; }
            set { isSummary = value; }
        }

        private bool isLastColumn;
        public bool IsLastColumn
        {
            get { return isLastColumn; }
            set { isLastColumn = value; }
        }

        private string formatString;
        public string FormatString
        {
            get { return formatString; }
            set { formatString = value; }
        }


        private HorizontalAlignment textAlign = HorizontalAlignment.Left;
        [DefaultValue(HorizontalAlignment.Left)]
        public HorizontalAlignment TextAlign
        {
            get { return textAlign; }
            set
            {
                textAlign = value;
                setFormatFlags();
            }
        }

        private StringTrimming trimming = StringTrimming.None;
        [DefaultValue(StringTrimming.None)]
        public StringTrimming Trimming
        {
            get { return trimming; }
            set
            {
                trimming = value;
                setFormatFlags();
            }
        }

        private void setFormatFlags()
        {
            format.Alignment = TextHelper.TranslateAligment(TextAlign);
            format.Trimming = trimming;
        }

        public Color BorderColor
        {
            get { return borderColor; }
            set { borderColor = value; }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            int subWidth = 0;
            Rectangle textBounds;

            if (!string.IsNullOrEmpty(formatString) && !string.IsNullOrEmpty(Text))
            {
                decimal num = Convert.ToDecimal(ConvertEx.replaceCurrency(Text));
                if (Text.Contains('%'))
                    num = decimal.Divide(num, 100);
                Text = String.Format("{0:" + formatString + "}", num);
            }

            textBounds = new Rectangle(this.ClientRectangle.X, this.ClientRectangle.Y, this.ClientRectangle.Width, this.ClientRectangle.Height);
            using (Pen pen = new Pen(borderColor))
            {
                if (isLastColumn)
                    subWidth = 1;

                e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
                e.Graphics.DrawRectangle(pen, this.ClientRectangle.X, this.ClientRectangle.Y, this.ClientRectangle.Width - subWidth, this.ClientRectangle.Height);
                e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), textBounds, format);
            }
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            if (TextChanged != null)
                TextChanged(this, e);
        }

    }
}
View Code

  4. 使用自定义表格 GridViewSummary,效果如下

DevExpress13.2.9 控件使用经验总结

 

四. Grid 自定义绘制操作列头

  1. 创建  修改列(operate_modify)、删除列(operate_del)

  2. 添加 GridView 方法  CustomDrawColumnHeader,绘制表头

DevExpress13.2.9 控件使用经验总结
/// <summary>
/// 自定义绘制操作列表头
/// </summary>
private void gvDetail_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
{
    if(e.Column != null)
    {
        if (e.Column == operate_modify)
        {
            e.Info.InnerElements.Clear();
            e.Painter.DrawObject(e.Info);
            e.Handled = true;

            int delColumnWidth = operate_del.VisibleWidth;
            e.Graphics.FillRectangle(new SolidBrush(e.Info.Appearance.BackColor), new Rectangle(e.Bounds.X - delColumnWidth + 1, e.Bounds.Y + 1, e.Bounds.Width + delColumnWidth - 2, e.Bounds.Height - 2));
            e.Graphics.DrawString("操作", new Font("宋体", 9f), new SolidBrush(e.Info.Appearance.ForeColor), new Rectangle((e.Bounds.X - delColumnWidth) + (e.Bounds.Width + delColumnWidth) / 2 - 15, e.Bounds.Y + 8, 30, 15));
        }        
    }
}
View Code

  3. 效果如下

DevExpress13.2.9 控件使用经验总结

 

五. Grid 绘制复选框和全选框

  1. 创建  复选框列(check)

  2. 添加 GridView 方法 CustomDrawCell,绘制复选框

DevExpress13.2.9 控件使用经验总结
/// <summary>
/// 自定义绘制删除、修改单元格
/// </summary>
private void gvDetail_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
    GridView currentView = sender as GridView;
    if (e.Column == check)
    {
        ControlPaint.DrawCheckBox(e.Graphics, new Rectangle(e.Bounds.X + e.Bounds.Width / 2 - 8, e.Bounds.Y + 3, 16, 16), checkBoxState[e.RowHandle]);
    }        
}
View Code

  3. 添加 GridView 方法 CustomDrawColumnHeader,绘制全选框

DevExpress13.2.9 控件使用经验总结
/// <summary>
/// 自定义绘制操作列表头
/// </summary>
private void gvDetail_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
{
    if(e.Column != null)
    {
        if (e.Column == check)
        {
            e.Info.InnerElements.Clear();
            e.Painter.DrawObject(e.Info);
            e.Handled = true;

            ControlPaint.DrawCheckBox(e.Graphics, new Rectangle(e.Bounds.X + e.Bounds.Width / 2 - 8, e.Bounds.Y + 6, 16, 16), allSelectState);
        }
    }
}
View Code

  4. 添加 GridView 方法 Click ,判断全选框是否被点击,若有则重绘所有复选框

DevExpress13.2.9 控件使用经验总结
/// <summary>
/// 判断Grid全选框是否被单击
/// </summary>
/// <param name="gridView"></param>
/// <param name="name"></param>
/// <returns></returns>
public bool ClickGridCheckBox(DevExpress.XtraGrid.Views.Grid.GridView gridView, string name)
{
    bool result = false;
    if (gridView != null)
    {
        DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info;
        Point pt = gridView.GridControl.PointToClient(Control.MousePosition);
        info = gridView.CalcHitInfo(pt);
        if (info.InColumn && info.Column != null && info.Column.Name == name)
        {
            return true;
        }
    }
    return result;
} 


private void gvDetail_Click(object sender, EventArgs e)
{
    if (ClickGridCheckBox(this.gvDetail, "check"))
    {
        allSelectState = allSelectState == ButtonState.Checked ? ButtonState.Normal : ButtonState.Checked;
        selCount = allSelectState == ButtonState.Checked?0:checkBoxState.Count;
        
        for (int i = 0; i < checkBoxState.Count; i++)
        {
            SetCheckBoxState(i, allSelectState);
        }
    }
}

/// <summary>
/// 重新绘制复选框
/// </summary>
/// <param name="rowHandle"></param>
/// <param name="state"></param>
private void SetCheckBoxState(int rowHandle, ButtonState state)
{
    checkBoxState[rowHandle] = state;
    //获取点击单元格左上角的坐标
    GridViewInfo info = gvDetail.GetViewInfo() as GridViewInfo;
    GridCellInfo cellInfo = info.GetGridCellInfo(rowHandle, check);

    ControlPaint.DrawCheckBox(gcDetail.CreateGraphics(), new Rectangle(cellInfo.Bounds.X + cellInfo.Bounds.Width / 2 - 8, cellInfo.Bounds.Y + 3, 16, 16), state);

}
View Code

  5. 效果如下

DevExpress13.2.9 控件使用经验总结