Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Разработка Windows Forms > DATAGRID


Автор: Springtime 29.4.2009, 14:56
Всем привет!
В общем интересует как сделать что бы текст в заголовках DataGrid сделать вертикальным, не предлагать метод Paint - 
http://www.astahost.com/info.php/vertical-...der_t12863.html
Т.к. необходимо что бы еще поддерживался перенос текста на новую строку!

Или подскажите компонент пофиг какой, который это поддерживает.

Пожалуйста!  smile 

Автор: Roha 30.4.2009, 15:55
DevExpress (XtraGrid) например.

Автор: Springtime 4.5.2009, 07:52
Цитата(Roha @ 30.4.2009,  15:55)
DevExpress (XtraGrid) например.

А ты можешь выложит принскрин, что бы я увидел что там это действительно есть, т.к. я что то это не нашел.

Автор: Roha 5.5.2009, 09:19
Выставляешь свойство ColumnPanelRowHeight - размер заголовка и прописываешь в коде события CustomDrawColumnHeader следующие 
Код

private bool vertical = true;
        private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            Rectangle r = e.Info.CaptionRect;
            e.Info.Caption = "";
            e.Painter.DrawObject(e.Info);
            if (e.Column != null)
            {
                System.Drawing.Drawing2D.GraphicsState state = e.Graphics.Save();
                StringFormat sf = new StringFormat();
                sf.Trimming = StringTrimming.EllipsisCharacter;
                sf.FormatFlags |= StringFormatFlags.NoWrap;
                if (vertical)
                    sf.FormatFlags |= StringFormatFlags.DirectionVertical;
                //if (diagonal) r = Transform(e.Graphics, 30, r);
                e.Graphics.DrawString(e.Column.Caption, e.Appearance.Font, e.Appearance.GetForeBrush(e.Cache), r, sf);
                e.Graphics.Restore(state);
            }
            e.Handled = true;
        }

Скрин во вложении

Автор: Roha 5.5.2009, 09:49
Забыл. Для переноса текста замени
Код

sf.FormatFlags |= StringFormatFlags.NoWrap;


на 
Код

sf.FormatFlags |= StringFormatFlags.NoClip;

Автор: Springtime 5.5.2009, 15:31
Большое спасибо!  smile 

Автор: Springtime 8.5.2009, 13:46
Roha еще раз тебе большое спасибо, почти всё получилось с обычным dataGridView, наследуя от DataGridViewColumnHeaderCell

Код

class CustumDataGridViewColumnHeaderCell : DataGridViewColumnHeaderCell

    {
        private Color cellColor;
        private Color textColor;
        public CustumDataGridViewColumnHeaderCell()
        {
        }
        public CustumDataGridViewColumnHeaderCell(Color cellColor, Color textColor)
        {
            this.cellColor = cellColor;
            this.textColor = textColor;
        }
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, String.Empty, String.Empty, errorText, cellStyle, advancedBorderStyle, paintParts);

            Rectangle r = new Rectangle(cellBounds.X, cellBounds.Y, cellBounds.Width, cellBounds.Height - 2);
           
            Color c = Color.FromArgb(200, cellColor);
            LinearGradientBrush b = new LinearGradientBrush(r, c, Color.White, 90);
            
            graphics.FillRectangle(b, r);
            
            Brush tBrush = new SolidBrush(this.textColor);
            Font f = new Font(cellStyle.Font, FontStyle.Bold);
            StringFormat StF = new StringFormat();
            StF.Trimming = StringTrimming.EllipsisCharacter;
            StF.Alignment = StringAlignment.Near;
            StF.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.DirectionVertical | StringFormatFlags.DirectionRightToLeft;
            //graphics.DrawString((string)value, f, tBrush, new PointF(cellBounds.X + 5, cellBounds.Y + 5),StF);
            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            graphics.DrawString((string)value, f, tBrush, r, StF);
        }
 
        public override object Clone()
        {
            CustumDataGridViewColumnHeaderCell c = (CustumDataGridViewColumnHeaderCell)base.Clone();
            c.cellColor = this.cellColor;
            return (c);
        }


и потом

Код

this.Column1 = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.Column1.HeaderCell = new Rigel.CustumDataGridViewColumnHeaderCell(System.Drawing.Color.AliceBlue, System.Drawing.Color.Black);


Получаем:
user posted image

В общем есть несколько вопросов:
1. Как мне повернуть текст на 180 градусов, т.е. что бы начало строки было не сверху, а с низу? Пытался с помощью RotateTransform,
Код

Rectangle r = new Rectangle(1-cellBounds.X, -1-cellBounds.Y, cellBounds.Width, cellBounds.Height);
graphics.TranslateTransform(cellBounds.Width, cellBounds.Height);
graphics.RotateTransform(180.0F);
 
но выходит какая то чушь. Текст переворачивается как надо, но начинаются косяки в виде артефактов. 

2. В общем при переопределении каких либо свойств у DataGridView средствами студии, код написанный тобой в Designer.cs
Код

this.Column1.HeaderCell = new Rigel.CustumDataGridViewColumnHeaderCell(System.Drawing.Color.AliceBlue, System.Drawing.Color.Black);

исчезает, что я заметил давно ), но не зная как этого избежать.
и
3. В общем DataGridView очень гибкий элемент, но проблемы с Designer.cs, меня убивают, не знаю что делать. Писать отдельный компонент, или можно как то еще связать то, что ты переопределил в нём, и одновременно пользоваться обычным редактором свойств? Для добавление ячеек, настройкой их отображения и т.д. 

В общем не знаю как действовать.

Автор: Roha 8.5.2009, 14:55
Посмотри это может поможет
http://msdn.microsoft.com/ru-ru/library/awacs0xh.aspx

Автор: Springtime 28.5.2009, 09:36
На здоровье:

Код

class CustumDataGridViewColumnHeaderCell : DataGridViewColumnHeaderCell
    {
        private Color cellColor;
        private Color textColor;
        String str;
        bool tr;
        public CustumDataGridViewColumnHeaderCell()
        { }

        public CustumDataGridViewColumnHeaderCell(Color cellColor, Color textColor, String str, bool tr)
        {
            this.cellColor = cellColor;
            this.textColor = textColor;
            this.str = str;
            this.tr = tr;
        }
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, String.Empty, String.Empty, errorText, cellStyle, advancedBorderStyle, paintParts);

            System.Drawing.Drawing2D.GraphicsState state = graphics.Save();

            Rectangle r = new Rectangle(cellBounds.X, cellBounds.Y, cellBounds.Width, cellBounds.Height);
            SolidBrush b = new SolidBrush(cellColor);
            graphics.FillRectangle(b, r);
            
            Brush tBrush = new SolidBrush(this.textColor);
            Font f = new Font(cellStyle.Font, FontStyle.Regular);
            StringFormat StF = new StringFormat();
            StF.Trimming = StringTrimming.EllipsisCharacter;

            Pen pen = new Pen(Color.Black, 1F);

            graphics.DrawRectangle(pen, cellBounds.X, cellBounds.Y, cellBounds.Width-1, cellBounds.Height-1);

            StF.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces;
            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            StF.LineAlignment = StringAlignment.Far;
            StF.Alignment = StringAlignment.Near;
            if(tr) 
            {
                r = Transform(graphics, -90, r);
                StF.LineAlignment = StringAlignment.Center;
                StF.Alignment = StringAlignment.Center;
            }

          //graphics.DrawString(str, f, tBrush, r, StF);
            graphics.DrawString(str, f, tBrush, r, StF);
            graphics.Restore(state);
        }
 
        public override object Clone()
        {
            CustumDataGridViewColumnHeaderCell c = (CustumDataGridViewColumnHeaderCell)base.Clone();
            c.cellColor = this.cellColor;
            return (c);
        }

        private Rectangle Transform(Graphics g, int degree, Rectangle r)
        {
            g.TranslateTransform(0, r.Height);
            g.RotateTransform(degree);
            Rectangle r1 = r;
            r1.X = r.Y;
            r1.Y = r.X;
            r1.Width = r.Height;
            r1.Height = r.Width;
            return r1;
        }
    }


Всё как надо.  smile 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)