[英]Dynamically Clone ToolStripMenuItem to ContexMenuStrip c# Winforms
我有一個可用的ToolStripMeniItem
菜單。
我還創建了一個ContextMenuStrip
並將其分配給PictureBox
我想將ToolStripMeniItem
的項目克隆/復制到ContextMenuStrip
我有以下代碼:
this.components = new System.ComponentModel.Container();
this.pbxPhoto = new System.Windows.Forms.PictureBox();
this.menuView = new System.Windows.Forms.ToolStripMenuItem();
this.ctxMenuView = new System.Windows.Forms.ContextMenuStrip(this.components);
this.menuView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuImage});
this.menuView.Name = "menuView";
this.menuView.Size = new System.Drawing.Size(53, 24);
this.menuView.Text = "&View";
this.menuImage.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuStretch,
this.menuActual});
this.menuImage.Name = "menuImage";
this.menuImage.Size = new System.Drawing.Size(126, 26);
this.menuImage.Text = "&Image";
this.menuImage.DropDownOpening += new System.EventHandler(this.menuImage_DropDownOpening);
private PictureBoxSizeMode[] modeMenuArray =
{
PictureBoxSizeMode.StretchImage,
PictureBoxSizeMode.Normal
};
private int _selectedImageMode = 0;
private void menuImage_DropDownOpening(object sender, EventArgs e)
{
if(sender is ToolStripMenuItem)
{
bool bImageLoaded = (pbxPhoto.Image != null);
foreach (ToolStripMenuItem mi in ((ToolStripMenuItem)sender).DropDownItems)
{
mi.Enabled = bImageLoaded;
mi.Checked = (this._selectedImageMode == mi.MergeIndex);
}
}
}
private void menuImage_ChildClick(object sender, EventArgs e)
{
if (sender is ToolStripMenuItem)
{
ToolStripMenuItem mi = (ToolStripMenuItem)sender;
_selectedImageMode = mi.MergeIndex;
pbxPhoto.SizeMode = modeMenuArray[mi.MergeIndex];
pbxPhoto.Invalidate();
}
}
private void DefineContextMenu()
{
foreach(ToolStripMenuItem mi in menuView.DropDownItems)
{
//ctxMenuView.Items.Add(mi.Name); // Debug 1
ctxMenuView.Items.Add(mi);
}
}
出於調試目的,如果我使用 Debug 1 注釋行,代碼工作正常:
其中“:”后面的意思是:集合被修改; 枚舉操作可能不會被執行。
我可以在我的代碼(函數DefineContextMenu()
)中做些什么來使其將ToolStripMenuItems
的內容傳輸到我的ContextMenuStrip
?
我剛剛找到了解決方案。 關鍵是首先創建一個ContextMenuStrip
,然后將其分配給ToolStripMenuItem
的DropDown
屬性。
關鍵代碼如下:
menuView.DropDown = ctxMenuView;
這是因為, ContextMenuStrip
類基於ToolStripDropDown
類,並定義了 Items 屬性來保存ToolStripItem
實例的集合; ToolsStripMenuItem
對象基於ToolStripDropDownItem
類,該類定義了一個包含ToolsStripDropDown
實例的DropDown
屬性。
有一天這可能會幫助某人。 我還意識到嘗試將項目添加到ContextMenu
。 Items 正在改變原始集合(實際上是從原始集合中刪除了該項目)。 使用AddRange
方法對我AddRange
。 由於它需要一個ToolStripItems
數組,我只是將每個DropDownItem
復制到一個數組中,然后將該數組傳遞給AddRange
方法。 您仍然需要將contextMenu
添加到menuView.DropDown
才能使其工作。
private void DefineContextMenu()
{
ToolStripItem[] toolArr = new ToolStripItem[menuView.DropDownItems.Count];
int count = 0;
foreach(ToolStripItem t in menuView.DropDownItems)
{
toolArr[count] = t;
count++;
}
ctxtMenuView.Items.AddRange(toolArr);
menuView.DropDown = ctxtMenuView;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.