根據documentation,您應該在將圖像從一種形式傳遞給另一種形式時創建圖像的克隆。喜歡的東西:
frmAdd.pctImage.Image = pctImage.Image.Clone() as Image;
編輯:作爲lumberjack4指出的那樣,你還可以創建一個新的,看不見的frmAdd
和圖像分配給這種形式,而不是已經所示。圖像可能實際上被正確分配(儘管您仍然應該克隆它),但它永遠不會在屏幕上顯示,因爲您的本地frmAdd
從不顯示。下面是一些代碼,會告訴你如何做到這一點:
在frmAdd
---------:
public partial class frmAdd : Form
{
// Stores a reference to the currently shown frmAdd instance.
private static frmAdd s_oInstance = null;
// Returns the reference to the currently shown frmAdd instance
// or null if frmAdd is not shown. Static, so other forms can
// access this, even when an instance is not available.
public static frmAdd Instance
{
get
{
return (s_oInstance);
}
}
public frmAdd()
{
InitializeComponent();
}
// Sets the specified picture. This is necessary because picAdd
// is private and it's not a good idea to make it public.
public void SetPicture (Image oImage)
{
picAdd.Image = oImage;
}
// These event handlers are used to track if an frmAdd instance
// is available. If yes, they update the private static reference
// so that the instance is available to other forms.
private void frmAdd_Load (object sender, EventArgs e)
{
// Form is loaded (not necessarily visible).
s_oInstance = this;
}
private void frmAdd_FormClosed (object sender, FormClosedEventArgs e)
{
// Form has been closed.
s_oInstance = null;
}
// Whatever other code you need
}
在frmNew ---------:
public partial class frmNew : Form
{
public frmNew()
{
InitializeComponent();
}
private void btnCancel_Click (object sender, EventArgs e)
{
// Is there an active instance of frmAdd? If yes,
// call SetPicture() with a copy of the image used by
// this frmNew.
frmAdd oFrm = frmAdd.Instance;
if (oFrm != null)
oFrm.SetPicture (picNew.Image.Clone() as Image);
}
}
有2 PictureBox
涉及對照:picAdd
在frmAdd
和picNew
在frmNew
。當點擊btnCancel
時,frmNew
中的代碼將檢查是否存在有效的frmAdd
實例,如果是,則設置其圖像。
請注意picAdd
不是公共控件 - 它應該是私人的。將控件設置爲公開形式並不是一個好主意,因爲它允許不受控制地訪問它們,並且表單不會確切地知道它們的狀態(因爲其他人可能會在沒有表單知道的情況下更改這些控件)。這可能導致變化很難在更大的程序中修復錯誤。
如果您需要訪問其窗體之外的控件,請將控件保留爲私有,並在需要時更新控件的形式中創建公共屬性/方法 - 如上面的SetPicture
方法。這仍然可以讓你從表單之外分配圖片,但是表單控制了這種情況的發生,因爲SetPicture
可以驗證圖像等。如果你只是將你的控件設置爲公開,這是不可能的。
仍然沒有工作... :( 我已經試過這個。 –
當你發生什麼事情 嘗試這個?你有沒有發現異常或者什麼都沒有顯示? – xxbbcc
只是沒有顯示.. –