如何在c-sharp中以编程方式将图像添加到Button?

如何在c-sharp中以编程方式将图像添加到Button?

问题描述:

大家好,

我正在做一个简单的项目.我需要将图像(jpg或bmp)添加到按钮.

我的问题:

我的本地驱动器中有一些图像.我知道我需要将这些图像添加到我正在工作的当前项目中,然后才能使用它.

由于我也有> 2个按钮,我想最好将图像添加到某种容器中,并使用其索引将其分配给适当的按钮.

1)如何将图像添加到项目中?
2)如何将这些图像添加到按钮?

谢谢,
Skunkhead:)

Hi guys,

I''m working on a simple project. I need to add images(jpg or bmp) to buttons.

My question:

I have some images in my local drive. I know that I need to add these images to current project that I''m working before it can be used.

Since I''m also having > 2 buttons, I guess it would be better to add the images to some kind of container and use its index to assign it to the appropriate button.

1) How can I add the images to the project?
2) How to add these images to buttons?

Thanks,
Skunkhead :)

如何向项目添加图像?

我的主要建议:不要使用Visual Studion图像编辑器执行此操作.这些图像将嵌入到资源文件中;它将使资源文件变得难以管理且难以支持.此外,周围还有一些更好的免费编辑器. (我建议使用GIMP和InkSkape(向量,但支持导出到任何东西,重要的是XAML)).因此,您创建了一些文件,并将它们放在项目中的某些资源目录中.在同一目录中,创建新的*.resx资源,然后单击添加资源"-> 添加现有文件",继续.您的图形文件将被添加到项目和资源中.使用资源节点下的自动生成的C#文件访问图像.更喜欢PNG.

如何在按钮上添加图像?

添加一个按钮.单击其属性.找到属性Image,然后单击省略号"按钮.它将显示您的资源和与按钮相关联的图像选择.

以编程方式...

How to add images to the project?

My main recommendation: do not do it using Visual Studion image editor. The images will be embedded in the resource file; it will render the resource file unmanageable and hard to support. Also, there are some much better free editors around. (I would recommend GIMP and InkSkape (vector, but supports exports to anything, importantly to XAML)). So, you create some files and put them in some resource directory within your project. In the same directory, create new *.resx resource and click "Add Resource" -> "Add Existing File", proceed. Your graphic files will be added to the project and to the resource. Use auto-generated C# files under resource node to access the images. Prefer PNG.

How to add images to buttons?

Add a button. Click its Properties. Locate the property Image and click on the "ellipsis" button. It will show you your resources and selection of the image to associate with the button.

Programmatically...

Panel parent = //... for example, panel is a button's parent
Button button = new Button();
button.Image = //... image reference, see resource's auto-generated class
button.Text = "Some &Text";
button.Width = //...
button.Top = //...
button.Left = //...
parent.Controls.Add(button); //at this moment it is shown



—SA



—SA