【发布时间】:2018-09-11 22:23:15
【问题描述】:
我正试图弄清楚如何使用 WInForm PictureBox 控件做一些事情。
我将简要描述我的应用程序是如何构建的,然后提出我的问题。
我使用的是 C# Visual Studio 2012,但 Visual Studio 的版本可能无关紧要。
创建一个名为“FunWIthPictureBox”的新 WinForms 应用程序。 调出表单的设计视图。
添加一个 PIctureBox 控件并将其命名为 pbxPicture。
点击图片框。您会注意到右上角有一个黑色箭头。
单击黑色箭头以调出 PictureBox 任务对话框。单击“选择图像”选项。
这将打开“选择资源”对话框。确保选中“项目资源文件”单选按钮。单击“导入”按钮以导入图像。完成后再次单击“导入”并添加第二张图像。最后点击“确定”。我的图片被命名为“Picture1.jpg”和“Picture2.jpg”。
现在您已将两个位图图像加载到项目的资源文件 (Properties\Resources.resx) 中。
双击表单以调出表单的加载事件。
您可以使用以下代码将图片框的图像设置为 Picture1.jpg... pbxPicture.Image = FunWIthPictureBox.Properties.Resources.Picture1; 请注意,“FunWithPictureBox”是命名空间。
如果你想使用另一张图片,你可以像这样更新代码行.. pbxPicture.Image = FunWIthPictureBox.Properties.Resources.Picture2;
好的,到目前为止一切都很好。我试图弄清楚如何提取所有已加载到 .Properties.Resources 中的图像并将这些图像加载到图像列表(List)中。
使用反射(和谷歌)我能够想出以下..
(使用 System.Reflection 添加)
private void PictureBoxForm_Load(object sender, EventArgs e)
{
pbxPicture.Image = FunWithPictureBox.Properties.Resources.Picture1;
var properties = typeof(Properties.Resources).GetProperties(BindingFlags.NonPublic | BindingFlags.Static);
foreach (var propertyinfo in properties)
{
if (propertyinfo.PropertyType.ToString() == "System.Drawing.Bitmap")
{
MessageBox.Show(propertyinfo.Name + " " + propertyinfo.PropertyType.ToString());
}
}
}
这几乎给了我想要的东西。我能够识别资源文件中的图像。
如何将这些图像添加到图像列表中?我有图像的名称,但我不知道如何访问图像并将其添加到列表中。
这样的……
private void PictureBoxForm_Load(object sender, EventArgs e)
{
List<Image> lstImages = new List<Image>();
pbxPicture.Image = FunWithPictureBox.Properties.Resources.Picture1;
var properties = typeof(Properties.Resources).GetProperties(BindingFlags.NonPublic | BindingFlags.Static);
foreach (var propertyinfo in properties)
{
if (propertyinfo.PropertyType.ToString() == "System.Drawing.Bitmap")
{
lstImages.Add(propertyinfo.Name); //This code does not wwork :-(
}
}
}
有没有办法做到这一点?
【问题讨论】:
-
这是一个非常详细的问题,只有一个答案。问题很明确,问题显示了已经完成的前期工作。否决这个问题的人有心理问题。投反对票的人可能没有很多朋友,我敢打赌他的母亲并不真正爱他。
标签: c# visual-studio visual-studio-2012 reflection