从test.cs

时间:2015-07-08 09:51:16

标签: c# forms picturebox

我正在尝试从另一个cs文件更新“form1”中的图片框图像 我在test.cs中的代码

slot_13.modifier = public;

并且在form1中我也写了这个

CheckForIllegalCrossThreadCalls = false;

test.cs中

inventory_Viewer.viewer x = new inventory_Viewer.viewer();
x.slot_13.Image = Image.FromFile(@"C:\Users\Axmed\Google Drive\C# Source Codes\inventory Viewer\inventory Viewer\bin\Release\icon\icon_default.png");

但它不起作用 如果我在“form1”

中使用此行
x.slot_13.Image = Image.FromFile(@"C:\Users\Axmed\Google Drive\C# Source Codes\inventory Viewer\inventory Viewer\bin\Release\icon\icon_default.png");

图片变了

1 个答案:

答案 0 :(得分:0)

你的代码错过了很多背景,所以我会做一些假设。给定一个MainForm显示InventoryViewerForm并且还想更改InventoryViewerForm上的图像,您可以保存对第二个表单的引用,如下所示:

// Your inventory_Viewer.viewer
public partial class InventoryViewerForm
{
    public InventoryViewerForm()
    {
    }
}

// The form from which to show the viewer. 
public partial class MainForm
{
    private readonly InventoryViewerForm _inventoryViewerForm;

    public MainForm()
    {
        _inventoryViewerForm = new InventoryViewerForm();
    }

    private void ShowInventoryViewerButton_Click(object sender, EventArgs e)
    {
        _inventoryViewerForm.Show();
    }

    private void ChangeImageButton_Click(object sender, EventArgs e)
    {
        // Dispose the previously loaded image.
        if (_inventoryViewerForm.Image != null)
        {
            _inventoryViewerForm.Image.Dispose();
        }

        _inventoryViewerForm.Image = Image.FromFile("NewImage.png");
    }
}

但这完全是糟糕的设计。您不希望像这样紧密地耦合您的表单,并且您希望利用WinForms的数据绑定和.NET的事件。为了正确实现这一点,您需要显示更多代码。