首页 > 解决方案 > C# 方法更改“图片框”

问题描述

试图更改“图片框”中的图像。但不会工作。没有错误,警告。

我有两种形式,一种是“消息框”,一种是主窗体。如果我尝试从另一种方法更改图像(例如:Form1_load)它可以工作。

表格1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1;
namespace jatek
{
    public partial class Form1 : Form
         public void Eldontesboss(short adat)
         {
            MessageBox.Show("Number:" + adat); //this is appears,but ...
            box.Image = WindowsFormsApp1.Properties.Resources.alap; //this is not work.
         }
    }
}

表格2:

using jatek;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
       private void button1_Click(object sender, EventArgs e)
        {
            Form1 foo = new Form1();
            foo.Eldontesboss(1);
            this.Close();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Form1 foo = new Form1();
            foo.Eldontesboss(2);
            this.Close();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            Form1 foo = new Form1();
            foo.Eldontesboss(3);
            this.Close();
        }   
    }
}

更改 PictureBox 图像。

标签: c#

解决方案


您正在创建的实例Form1永远不会显示;它们在记忆中是不可见的。如果要更改当前显示的 PictureBox 中的图像Form1则需要对该特定实例的引用。从您的描述中不清楚哪种形式是“主要”形式,哪种形式是“消息”形式,但我认为 Form1 是主要形式,而 Form2 是消息。此外,我假设 Form1 正在创建 Form2 的一个实例。如果是这种情况,传递引用的一种方法是Owner在调用时设置属性Show(),如下所示:

// ... in Form1, when Form2 is created ...
Form2 f2 = new Form2();
f2.Show(this); // pass reference to Form1, into Form2

现在,在 Form2 中,您可以将Owner属性转换回类型Form1并使用它:

// ... in Form2, after being displayed with `Show(this)` back in `Form1` ...
private void button1_Click(object sender, EventArgs e)
{
    Form1 foo = (Form1)this.Owner;
    foo.Eldontesboss(1);
    this.Close();
}

推荐阅读