将PictureBox的图像从我的资源更改为图像?

Mas*_*tic 26 c# resources image picturebox winforms

如何从我的资源中将PictureBox图像设置为图像?

(我想这没有成功:pictuerbox.Image = "img_location";)

Ken*_*nde 65

如果使用visual studio UI加载资源,那么您应该能够这样做:

picturebox.Image = project.Properties.Resources.imgfromresource
Run Code Online (Sandbox Code Playgroud)

  • +1 - 我不得不调用`pictureBox.Load();`来显示图像,只从资源中分配它不起作用 (8认同)

小智 11

Ken有正确的解决方案,但您不想添加picturebox.Image.Load()成员方法.

如果使用Load执行此操作并且未设置ImageLocation,则它将失败并显示"必须设置映像位置"异常.如果你使用picturebox.Refresh()成员方法,它没有例外.

完成的代码如下:

public void showAnimatedPictureBox(PictureBox thePicture)
{
            thePicture.Image = Properties.Resources.hamster;
            thePicture.Refresh();
            thePicture.Visible = true;
}
Run Code Online (Sandbox Code Playgroud)

它被调用为:showAnimatedPictureBox(myPictureBox);

我的XAML看起来像:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
        Title="myApp" Height="679.079" Width="986">

        <StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
            <wfi:WindowsFormsHost>
                <winForms:PictureBox x:Name="myPictureBox">
                </winForms:PictureBox>
            </wfi:WindowsFormsHost>
            <Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
        </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

我意识到这是一个旧帖子,但是直接从资源加载图像在微软的网站上是非常不清楚的,这是我得到的(部分)解决方案.希望它可以帮到某人!

  • 尽可能使用 thePicture.Invalidate() 而不是 Refresh()。这允许应用程序在认为需要绘制时绘制它。Refresh() 强制它立即绘制它,这通常不是最好的性能...... (2认同)

Ali*_*eon 6

好的...首先,您需要在项目中导入图像

1)在"表单设计"中选择图片框

2)打开PictureBox任务(这是在图片框边缘右侧固定的小箭头)

3)点击"选择图片..."

4)选择第二个选项"Project resource file:"(此选项将创建一个名为"Resources"的文件夹,您可以使用Properties.Resources访问该文件夹)

5)单击导入并从计算机中选择图像(现在,将在步骤4中创建的Resources文件夹中发送与图像同名的图像副本)

6)点击确定

现在图像在您的项目中,您可以将它与属性命令一起使用.当您想要从图片框更改图片时,只需输入以下代码:

pictureBox1.Image = Properties.Resources.myimage;
Run Code Online (Sandbox Code Playgroud)

注意:myimage代表图像的名称...在资源之后键入点后,在您的选项中它将是您导入的图像文件