I have extended a PictureBox and created a singleton.
Is it possible to 开发者_运维问答display the same instance of a PictureBox control on two distinct form same time ?
Thanks in advance.
No - a control has a single parent control.
Of course not. Each Control has Parent property (and underlying window has parent window). Control has to communicate with its parent.
Having said that, if you need ImageControls on different forms to display the same image, here's what you can do.
Approach A
1) Create a (global) list of these picture boxes in your application.
class Globals //or whatever
{
public static List<PictureBox> allBoxes=new List<PictureBox> ();
2) On form creation add each PictureBox to this list.
foreach (Control c in Controls)
{
PictureBox pb = c as PictureBox;
if (pb != null) Globals.allBoxes.Add(pb);
}
3) when you need to change the image, iterate through this list:
foreach (PictureBox p in Globals.allBoxes)
{
p.Image=myImage;
}
I tested it a little, and it seems that you don't need to clone the image.
Approach B
1) Choose one 'master' PictureBox in your application. 2) Subclass PictureBox, so that it fires an event ImageChanged whenever Image property is set (some code samples in this thread) 3) On every other form having PictureBoxes, add an event handler to ImageChanged event of that 'master box' (masterBox.OnImageChanged+=new EventHandler(ImageChanged); 4) In the handler change all images
I prefer approach A.
I'm guessing you want to show the same picture in both pictureboxes? Take a look at the help file (take particular interest in the NOTE section).
PictureBox help
Remarks
Typically the PictureBox is used to display graphics from a bitmap, metafile, icon, JPEG, GIF, or PNG file.
Set the Image property to the Image you want to display, either at design time or at run time. You can alternatively specify the image by setting the ImageLocation property and load the image synchronously using the Load method or asynchronously using the LoadAsync method. NoteNote:
If you want to use the same image in multiple PictureBox controls, create a clone of the image for each PictureBox. Accessing the same image from multiple controls causes an exception to occur.
If your are trying to display a Logo on each form then I would subclass the Picturebox and just load the image into it. No singleton, no magic.
But be carefull: You have to load the Image for each PictureBox. From MSDN:
http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.image.aspx
The Image property is set to the Image to display. You can do this either at design time or at run time.
Note: If you want to use the same image in multiple PictureBox controls, create a clone of the image for each PictureBox. Accessing the same image from multiple controls causes an exception to occur.
精彩评论