【问题标题】:How to change a PictureBox image from another Form如何从另一个窗体更改 PictureBox 图像
【发布时间】:2019-05-22 16:01:18
【问题描述】:

我想在加载form1 时打开form2。另外,我想在form1 中触发操作时更改form2 中的图片框的图像。

要在 form1 加载时打开 form2,我使用了以下代码:

private void MONITOR3_Load(object sender, EventArgs e)
{
    MONITOR4 mo4 = new MONITOR4(this);
    mo4.Show();
}

要更改form2中PictureBox的Image,我使用了这段代码,必须在满足条件后运行:

if (textBox1.Text == @"QUEBEC - ALPHA - TANGO - ALPHA - ROMEO - ")
{
    MONITOR4 mo4 = new MONITOR4(this);
    mo4.pictureBox1.Image = Image.FromFile("D:/QResources/images/HIA.jpg");
}

【问题讨论】:

  • 你可以保留第一个sn-p作为参考,去掉另外两个,他们错了。您应该改为显示 Form1 中的哪些操作会触发 Form2 中的更改。
  • 我没听懂你
  • 我的意思是你应该edit your question,留下第一个代码sn-p(private void MONITOR3_Load (...)等)来表明你的意图。其他两个 sn-ps 没有用,因为它们是错误的。然后,您说要根据form1 中发生的操作更改form2 中pictureBox 中的图像。您应该显示执行此动作的时间/地点以及它是什么。这是需要添加到您的问题中的重要部分。
  • 那么你的代码有什么问题,你得到了什么错误?

标签: c# winforms picturebox


【解决方案1】:

您当前的代码有两个问题:

  • 您不必在每次需要设置其某些属性时都创建新的 Form 实例:存储对此 Form 的引用并使用此引用来调用 Form 的公共属性或方法。
  • 您正试图直接访问另一个窗体的子控件的属性。事件虽然您可以定义子控件public,但您不应该也没有必要。在这方面,Form 与任何其他类一样:在 Form 上创建一个公共方法,提供修改私有属性的方法,而无需直接将 Control 的属性暴露给直接访问。
    它更简单、更安全且更便携:如果需要修改 Control(名称更改、Control 类型更改等),您无需四处寻找旧名称/属性已在其他类中使用。
    公共方法将是相同的,它是唯一负责引用受影响控件的当前名称和属性的方法。最终需要修改代码的地方。 您还可以使用公共事件或实现INotifyPropertyChanged 来通知订阅者某些属性已更改。

在这里,我在Monitor3 表单中创建了对Monitor4 的引用:

Monitor4 mo4 = null;

此引用将用于调用 Monitor4 的公共方法 (UpdatePictureBox)。

Monitor3 表格:
(我正在使用 TextBox 的 TextChanged 事件来选择要在 Monitor4 PictureBox 中显示的图像。当然,它可以是 Validate 事件或任何其他符合您设计的内容)

public partial class Monitor3 : Form
{
    Monitor4 mo4 = null;

    private void Monitor3_Load(object sender, EventArgs e)
    {
        mo4 = new Monitor4();
        //Show Monitor4 on the right side of this Form
        mo4.Location = new Point(this.Right + 10, this.Top);
        mo4.Show(this);
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string newText = textBox1.Text;
        switch (newText) {
            case "[Some text 1]":
                mo4.UpdatePictureBox(@"[Images1 Path]");
                break;
            case "QUEBEC - ALPHA - TANGO - ALPHA - ROMEO - ":
                mo4.UpdatePictureBox(@"[Images2 Path]");
                break;
            case "[Some text 3]":
                mo4.UpdatePictureBox(@"[Images3 Path]");
                break;
        }
    }
}

Monitor4表格:

public partial class Monitor4 : Form
{
    public void UpdatePictureBox(string imagePath)
    {
        if (File.Exists(imagePath)) {
            pictureBox1.Image?.Dispose();
            pictureBox1.Image = Image.FromFile(imagePath, true);
        }
    }
}

示例结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-28
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    相关资源
    最近更新 更多