Aligning the text in the center vertically of a contextmenustrip item with manually set height
I'm trying to align the text in the centre vertically in acontextmenustrip item with manually set height of 60. However no matter what I try the text is always at the top开发者_运维问答. Images in the same item will align themselves correctly with out me doing anything.
I've tried the following:
foreach (ToolStripItem item in ContextMenuStrip1.Items)
{
item.AutoSize = false;
item.Height = 60;
item.Width = maxWidth;
item.TextAlign = ContentAlignment.MiddleCenter;
}
and creating a new customeRender class:
public sealed class CustomRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item.IsOnDropDown)
{
e.TextFormat |= TextFormatFlags.VerticalCenter;
}
base.OnRenderItemText(e);
}
}
However this doesn't work for me. The text remains vertically at the top of the item. An image added to one of these items gets centered, as to the arrow for more.
Any help would be great. Aidan
Use a ToolStripButton instead of a ToolStripItem - text alignment seems to work fine on this control
var b = new ToolStripButton("Hello");
b.TextAlign = ContentAlignment.MiddleCenter;
contextMenuStrip1.Items.Add(b);
I had the same issue in vertically aligning text in custom height menu items, after research I found that increasing the menu item height will not increase the height the text rectangle that represents the bounds to draw the text. To fix this inflate the text rectangle in OnRenderItemText in the custom render.
Protected Overrides Sub OnRenderItemText(e As ToolStripItemTextRenderEventArgs)
Dim r = e.TextRectangle
r.Height = e.Item.Height - 4 '4 is the default differnce between the item height and the text rectangle height
e.TextRectangle = r
e.TextFormat = TextFormatFlags.VerticalCenter
MyBase.OnRenderItemText(e)
End Sub
The result
精彩评论