在运行时切换UI资源

时间:2015-10-24 02:23:11

标签: c# winforms

我正在使用带有图标(图像)按钮的WinForms UI。目前,我刚刚使用Visual Studio设计器中的Image属性为每个按钮分配了图标图像。但是,我希望能够在运行时切换到不同的图标集/主题。我在stackoverflow上看到的各种方法仅适用于运行时,即代码加载相应的资源程序集,然后为每个按钮加载相应的图像资源并将其分配给按钮。这样做有自动方式吗?基本上,我想避免编写我加载每个资源的部分并将其分配给特定按钮。

1 个答案:

答案 0 :(得分:1)

您可以使用多个ImageList来包含不同的主题图片,然后将这些图片列表用作不同主题的按钮的图像源。为此:

  • 为每个主题
  • 创建ImageList
  • 将每个Tag的{​​{1}}属性设置为主题名称。 (您无法在运行时按名称访问组件,组件的name属性仅用于设计时,因此请设置ImageList属性以通过标记访问它们)
  • 将png图像的Tag属性设置为32位,将位图图像设置为24位
  • 设置图像的名称,并为不同图像列表中的相同图像使用相同的名称,例如,对于所有图像列表中的添加按钮的图像,使用"添加"名称
  • 设置按钮的ColorDepth属性,并在设计时设置ImageListImageIndex属性。首选使用ImageKey属性,因为如果ImageKey中没有该密钥,则它不会显示该按钮的图像。
  • 在运行时更改ImageList属性,以获取按钮的不同图像。

例如,您可以使用此代码在运行时更改所有按钮的ImageList

ImageList

以下是用法:

private IEnumerable<Control> GetAllControls(Control control)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}

private void ChangeTheme(string themeName)
{
    GetAllControls(this).OfType<Button>().ToList()
        .ForEach(btn =>
        {
            btn.ImageList = this.components.Components
                                .OfType<ImageList>()
                                .Where(x => Convert.ToString(x.Tag).ToLower() == themeName.ToLower())
                                .FirstOrDefault();
        });
}

它会将所有按钮的图片列表设置为this.ChangeTheme("theme1"); ,其ImageList属性值为Tag

相关问题