views:

330

answers:

3

I have a simple windows Forms application where in I have a usercontrol called "MyControl" derived from PictureBox.

In this MyControl, I have the following code :

Sub New()
   MyBase.New()
   Me.BackgroundImage = My.Resources.MyImage 'This is a project resource image
End Sub

Now when I drag and drop this MyControl into a form, I get the image and also those stuff. But the problem is that the BackgroundImage is being copied into the Form's local .resx file. So when I look into the form.designer file, I find the following :

Me.MyControl1.BackgroundImage = CType(resources.GetObject("MyControl1.BackgroundImage"), System.Drawing.Image)

This is a problem and also when I try to change the image in the control, it does not get reflected in the form's control instance. So this is a pain.

How can this be solved? Guess this is going to be trial and error research, but please help.

A: 

You must remove the background image from "MyControl" and just put the image in all the instances that you create.

If you use a lot the MyControl with the default image create a descendant from MyControl with that image and use it only as a MyControl with default image (you can consider it as readonly). When another image is needed just use the MyControl without default.

SoMoS
A: 

could you remove the Me.BackgroundImage = My.Resources.MyImage from constructor and move it to the overrided OnLoad control's method and retry your DragDrop?

Really, I don't think it will change a lot, but this approach seems to me more correct.

serhio
I tried this. But the controls do not have OnLoad method in them. I tried by overriding the OnCreateControl() method. But still it copies into the form's resource
Xinxua
+2  A: 

You have to tell the designer that it should not serialize the value of the BackgroundImage property. You do this by using the <DesignerSerializationVisibility> attribute:

Imports System.ComponentModel

Public Class MyControl
  Inherits Control

  Public Sub New()
    Me.BackgroundImage = My.Resources.MyImage
  End Sub

  <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
  <Browsable(false)> _
  Public Overrides Property BackgroundImage() As System.Drawing.Image
    Get
      Return MyBase.BackgroundImage
    End Get
    Set(ByVal value As System.Drawing.Image)
      MyBase.BackgroundImage = value
    End Set
  End Property
End Class

I also used the <Browsable> attribute, it no longer makes sense for the user to change the image since changes won't be persisted anymore.

Hans Passant
Nice, i was cursing .NET because of this ;)
Xinxua