如何将资源图像更改为具有相同名称但后缀不同的图像?

时间:2013-07-04 13:40:41

标签: c# .net winforms

我有ToolStrip ContextMenu,如此:

我的资源中有2个图标,如下所示:

我正在尝试将图标切换为16x16版本:

void largeIconsToolStripMenuItem_Click(object sender, EventArgs e)
{
    var ContextItem = (ToolStripMenuItem) sender;
    var ContextMenu = (ContextMenuStrip) ContextItem.Owner;
    var ToolStrip = (ToolStrip) ContextMenu.SourceControl;
    var Checked = ContextItem.Checked;

    ToolStrip.ImageScalingSize = Checked ? new Size(32, 32) : new Size(16, 16);

    foreach(ToolStripButton Button in ToolStrip.Items)
        Button.Image = Resources.t_new16;
}

这样可行,但我不想在foreach中为每个单独的图标添加新行。如何将资源名称替换为t_icon16,目前位于t_icon32

我尝试在Name中寻找Button.Image属性,但没有。{/ p>

我也尝试过:

foreach(ToolStripButton Button in ToolStrip.Items)
    foreach(PropertyItem P in Button.Image.PropertyItems)
        MessageBox.Show(P.Id.ToString() + " - " + P.Value.ToString());

但没有显示MessageBox

如何动态交换资源图片?

2 个答案:

答案 0 :(得分:1)

创建两个图像列表 - 一个带有小图标,另一个带有大图标(按相同顺序):

toolStrip.ImageList = smallImageList;
toolStripButton1.ImageIndex = 0;
toolStripButton2.ImageIndex = 1;

只需在列表之间切换:

toolStrip.ImageList = largeImageList;

答案 1 :(得分:0)

我设法做到这一点,而不必维护2个图像列表。

首先,ToolStripButton需要将其Tag属性设置为初始资源的名称:

使用该集,此代码动态处理其余部分:

void largeIconsToolStripMenuItem_Click(object sender, EventArgs e)
{
    var ResourceManager = new ResourceManager(typeof(Resources));
    var ContextItem = (ToolStripMenuItem) sender;
    var ContextMenu = (ContextMenuStrip) ContextItem.Owner;
    var ToolStrip = (ToolStrip) ContextMenu.SourceControl;
    var Checked = ContextItem.Checked;

    ToolStrip.ImageScalingSize = Checked ? new Size(32, 32) : new Size(16, 16);

    foreach(ToolStripButton Button in ToolStrip.Items)
    {
        var CurrentResource = Button.Tag.ToString();
        var NewResource = CurrentResource.Substring(0, CurrentResource.Length - 2) + (Checked ? "32" : "16");
        Button.Image = (Image) ResourceManager.GetObject(NewResource);
        Button.Tag = NewResource;
    }
}