加载布尔按钮的各种图像?

时间:2013-06-11 06:03:50

标签: c# .net winforms user-interface

我在运行时创建按钮,我想为每个值添加一个图像true和false, 所以,如果我有onOff按钮,则true为绿色图片,为假红色。并希望这也适用于其他属性。

我的问题是 1.如何加载图片以达到最佳效果? 2.如何以正确的方式创建按钮? 如果它看起来很奇怪,我对Enum按钮使用相同的功能。 我确定我做了很多错事,请指教。

foreach(p in properties){
if(p is bool){createBoolButton(p);}
//so on

string path;
string path2;
private Control createBoolButton(IProperty p) {
  countControls2 = 1;
  locationY = 10;
  int gbHeight = 2;
  radioButtonY = 10;
  IType pType = p.Type;
  var myP = new MyProperty(p, this);
  if (myP.Value != null) {
  }
  Panel gb = new Panel();
  gb.Location = new Point(locationY, nextLocationX);
  nextLocationX += rbWidth + 10;
  gb.Name = "groupBox" + p.Id;
  gb.Text = p.Id;
  gb.Tag = p;
  bool[] x = { true, false };
  foreach (var t in x) {
    RadioButton rb = new RadioButton();
    rb.Appearance = Appearance.Button;
    rb.Width = rbWidth;
    rb.Height = rbHeight;
    rb.Name = t.ToString();
    rb.Text = t.ToString();
    rb.Tag = t;
    countControls++;
    rb.Location = new Point(radioButtonY, radioButtonX);
    if (myP.Value != null && myP.Value.ToString().SafeEquals(rb.Text)) {
      rb.Checked = true;
    }
    radioButtonY += rbHeight;
    gb.Controls.Add(rb);
    rb.CheckedChanged += rb_CheckedChanged;
  }
  gb.Width = rbHeight * gbHeight + 20;
  gb.Height = rbWidth + 10;
  Controls.Add(gb);
  countControls2++;
  return gb;
}
  private void getimagesPath(EnumValue[] TypesArray) {

  foreach (var enumType in TypesArray) {
    string path = @"C:\Folder\" + enumType.Name + ".png";
    string path2 = @"C:\Folder\" + enumType.Name + "_checked.png";
    FileInfo fi = new FileInfo(path);
    FileInfo fi2 = new FileInfo(path2);
    if (!imagePaths.ContainsKey(enumType.Name) && !imagePaths.ContainsKey(enumType.Name + "_checked")) {
      if (fi.Exists && fi2.Exists) {
        imagePaths.Add(enumType.Name, path);
        imagePaths.Add(enumType.Name + "_checked", path2);
      }
    }
    else {
      if (!imagePaths.ContainsKey(enumType.Name)) {
        imagePaths.Add(enumType.Name, DEFAULT_IMAGE_PATH);
      }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

  1. 我认为在这种情况下你不需要图片。只需更改按钮的backColor。

  2. 创建按钮的示例代码:

    Dim pnl as new Panel
    
    Dim btn as new Button
    btn.Name = "btn1"
    btn.Location = new Point(..., ...)
    
    pnl.Controls.Add(btn)
    
  3. 抱歉,但我不知道C#。

答案 1 :(得分:0)

您应该将checked imageunchecked image保存为项目中的Resources。只需查看Solution Explorer,您将看到项目节点下的Resources节点下有一个Properties节点。双击该节点,您应该知道如何将图像添加到Resources。向其添加图像后,您可以轻松访问这些图像,如下面的代码所示。我认为您选中的已检查图片已添加到名称为Resources的{​​{1}},而未经检查的图片会添加到CheckedImage,其名称为Resources

UncheckedImage

您的代码冗余太多而且效率不高。