Я хочу создать пользовательский DataGridViewCell
, который выглядит как этот пример
![enter image description here](https://i.stack.imgur.com/5m0cE.png)
Я начал создавать эту ячейку.Сначала я наследую от 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](https://i.stack.imgur.com/1zACI.png)
Важной частью является второй столбец.Кнопка управления заполняет остальную часть ячейки.
Есть ли способ сделать кнопку размером с ее текст (ширина по умолчанию) и выровнять ее по правой стороне?