выровненная по правому краю кнопка на пользовательском DataGridViewButtonCell - PullRequest
0 голосов
/ 19 ноября 2018

Я хочу создать пользовательский DataGridViewCell, который выглядит как этот пример

enter image description here

Я начал создавать эту ячейку.Сначала я наследую от DataGridViewButtonCell и переопределяю важные методы.

    private class DataGridViewAllocationCell : DataGridViewButtonCell
    {
        public void Initialize() // Pseudo Constructor with some arguments
        {
            contextMenu = new ContextMenuStrip();
            // fill the contextMenu here
        }

        private ContextMenuStrip contextMenu;

        private const string BUTTON_TEXT = "...";

        private DataGridViewAllocationColumn ParentColumn { get { return OwningColumn as DataGridViewAllocationColumn; } }
        private int LabelWidth { get { return TextRenderer.MeasureText(FieldName, ParentColumn.DefaultCellStyle.Font).Width; } }

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentBackground & ~DataGridViewPaintParts.ContentForeground);
            Rectangle displayRectangle = DataGridView.GetCellDisplayRectangle(ParentColumn.Index, rowIndex, false);
            Rectangle cellRectangle = GetContentBounds(rowIndex);
            Rectangle labelRectangle = new Rectangle(displayRectangle.Location, new Size(LabelWidth, displayRectangle.Height));
            cellRectangle.Offset(displayRectangle.Location);
            base.Paint(graphics, clipBounds, cellRectangle, rowIndex, elementState, value, BUTTON_TEXT, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.All);
            TextRenderer.DrawText(graphics, FieldName, cellStyle.Font, labelRectangle, cellStyle.ForeColor);
        }

        protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
        {
            Rectangle rectangle = base.GetContentBounds(graphics, cellStyle, rowIndex);
            return new Rectangle(rectangle.Left + LabelWidth, rectangle.Top, rectangle.Width - LabelWidth, rectangle.Height);
        }

        protected override void OnContentClick(DataGridViewCellEventArgs e)
        {
            base.OnContentClick(e);
            Rectangle contentRectangle = GetContentBounds(e.RowIndex);
            Rectangle displayRectangle = DataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
            Point location = new Point(displayRectangle.Left + contentRectangle.Left, displayRectangle.Top + contentRectangle.Bottom);
            contextMenu.Show(DataGridView, location);
        }
    }

При создании столбца с этими ячейками я получаю эту сетку

enter image description here

Важной частью является второй столбец.Кнопка управления заполняет остальную часть ячейки.

Есть ли способ сделать кнопку размером с ее текст (ширина по умолчанию) и выровнять ее по правой стороне?

1 Ответ

0 голосов
/ 19 ноября 2018

Я бы посоветовал вам воспользоваться методом переопределения DataGridViewTextBoxCell и вставкой кнопки, когда она находится в фокусе, а не переопределением DataGridViewButtonCell и рисованием текстовой части.

Увы, то, что вы там сделали, все еще действует, и если вы хотите, чтобы кнопка выровнялась по-другому, вам просто нужно указать различные границы содержимого, т.е. вместо:

return new Rectangle(rectangle.Left + LabelWidth, rectangle.Top, rectangle.Width - LabelWidth, rectangle.Height);

Вы можете что-то поставитьнапример, выровненная по правому краю кнопка шириной 22 пикселя:

return new Rectangle(rectangle.Width - 22, rectangle.Top, 22, rectangle.Height);

И ваша кнопка будет вести себя как типичная кнопка "...", которую вы ожидаете.В любом случае, в этом и заключается ключ к вашей проблеме.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...