I am dynamically populating a ContextMenuStrip control but the
ContextMenuStrip does not adjust its own width according to the width of the
items contained in it.
This is what I do:
* I have created my own afxToolStripItem class which inherits from
ToolStripButton. I want my toolstrip items to contain additional properties.
* I have a utility class that will fetch data from the DB and create a list
of afxToolStripItem objects
* In the same utiltiy class the list of afxToolStripItem objects will be
added to the ContextMenuStrip control.
//Fetching and adding the tool strip items to the context menu strip
List<System.Windows.Forms.ToolStripItem> items =
GetContextMenuItems(contextMenuName);
contextMenu.Items.Clear();
foreach (ToolStripItem item in items)
{
item.Click += onClickEvent;
contextMenu.Items.Add(item);
//It seems the context menu's width is not always set
according to its largest child element
if (contextMenu.Width < item.Width)
contextMenu.Width = item.Width;
}
What I noticed is this: After construction and setting the ToolStripItem's
text property its width is 23 regardless of the length of its text. As soon
as I add the ToolStripItem to the ContextMenuStrip object the
ToolStripItem.Width property changes to reflect the length of its text.
After all of the toolstrip items have been added, the context menu's width
has not changed, causing only a portion of the text to display when the user
right-clicks.
The "if (contextMenu.Width < item.Width)" logic above is a workaround that
seems to do the trick, except for the very first time. When the very first
item is added "contextMenu.Items.Add(item);" its width property does not
change.
Has anyone experienced this before? Maybe have some advice?
Thanks in advance!