如何在Combobox

时间:2015-05-06 13:05:52

标签: c# image winforms combobox flowlayoutpanel

如果在ComboBox中选择了FlowLayoutPanel,如何使用按钮添加图标(适用于家中的设备)。 ComboBox包含不同设备的列表,当您选择一个设备时,额定功率会显示在TextBox中。

是否可以在FlowLayoutPanel中存储此信息和图标?

但是,我不确定FlowLayoutPanel是否是执行此操作的正确选项。

1 个答案:

答案 0 :(得分:0)

  

是否可以将此信息和图标存储在流程布局面板中?

不是真的,因为面板是用来存储UI控件,而不是任意数据。您可以当然可以解决这个问题。

执行此操作的一种方法是使用包含Image的自定义对象的备份列表。下面的代码定义了这样一个类(每个项目都有一个标题和图像),并使用此信息和一些事件挂钩在面板中填充基于组合框的图像,然后根据点击次数在文本框中设置文本图像。

public partial class Form2 : Form
{
    List<Item> itemList = new List<Item>();



    public Context c = new Context();
    public Form2()
    {
        InitializeComponent();

        itemList.Add(new Item("First"));
        itemList.Add(new Item("Second"));
        itemList.Add(new Item("Third" ));
        comboBox1.DataSource = itemList;
        comboBox1.DisplayMember = "Title";

        foreach (var itemView in itemList)
        {
            itemView.onClick += this.ItemClicked;
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var s = (ComboBox) sender;
        flowLayoutPanel1.Controls.Add(itemList[s.SelectedIndex].ThisImage);
    }

    private void ItemClicked(object sender, EventArgs e)
    {
        Item v = (Item)sender;
        AssignTextBox(v.Title);
    }

    public void AssignTextBox(string text)
    {
        textBox1.Text = text;
    }
}

public class Item
{
    public string Title { get; set; }
    public PictureBox ThisImage { get; set; }

    public delegate void clicked(object sender, EventArgs e);

    public event clicked onClick;

    public Item(string title)
    {
        Title = title;
        ThisImage = new PictureBox();
        ThisImage.Paint += Paint_This;
        ThisImage.Click += onClicked;
    }

    public void onClicked(object sender, EventArgs e)
    {
        if (onClick != null)
            onClick(this, e);
    }

    private void Paint_This(object sender, PaintEventArgs e)
    {
        using (Font f = new Font("Verdana", 14))
        {
            e.Graphics.DrawString(Title, f, Brushes.Black, new Point(1,1));
        }
    }

}