property with defalut value will not be called in auto-generated code, and how to make a property on

R

Ryan Liu

Hi,

What is the best practise to sove this problem:

property with defalut value will not be called in auto-generated code

?

for example

there is a property in a user control

private bool normalMode = false;
public bool NormalMode
{
get
{
return this.normalMode ;
}
set
{
SetAsNormal(value);
this.normalMode = value;
}

If I put this user control in a form, in forms InitializeComponent(), there
is no code like
userControl1.NormalMode = false;

so line like SetAsNormal(value); will not be called.

What is the best way to solve this? And how to make a property only visible
at design time?

Thanks a lot!
Ryan Liu
 
M

Marc Gravell

Re the default value, I would simply ensure that this code gets called
in the ctor.

Re the design time... pass.

Marc
 
N

Nicholas Paldino [.NET/C# MVP]

Ryan,

The only way that this will get called is if you have a value that is
different from the default value. You need to do this:

private bool normalMode = false;

[DefaultValue(false)];
public bool NormalMode
{
get
{
return this.normalMode ;
}
set
{
SetAsNormal(value);
this.normalMode = value;
}
}

Then, the designer will set the value for your component in
InitializeComponent method when you set a value to something OTHER than the
default value. If it is NOT the default value, then it ^will^ not and
^should^ not be set.

If you have a need for SetAsNormal(value) to be called, then in your
constructor, you should call SetAsNormal(normalMode).

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top