views:

169

answers:

2

What's the best way to avoid (or control) the initialisation by the designer of a heavy custom property in .NET? Sometimes it is important to have a property set to something initially without that setting being acted upon when initially set.

In the imaginary example below, I want to achieve the flexibility of having something like UpdateSetting as a property, but not the inconvenience of having the database set to zero every time the application starts up. All I can think of is another property that unlocks a flag.

public class A : UserControl
{
  public int UpdateSetting 
  {
    // Write to database or some such thing
  }

...

  public void InitializeComponent()
  {
    A a = new A();
    a.UpdateSetting = 0;  // Causes database write
  }
}
+1  A: 
[Default(0)]
public int UpdateSetting 
{
    get { /*...*/}
    set {/* Write to database or some such thing... */ }
}

This will make it show 0 in the designer initially (and show it in bold if you set it back to 0 after changing it) without every actually setting anything in code.

Joel Coehoorn
http://stackoverflow.com/questions/2290746/what-namespace-is-the-default-attribute-for-properties-on-usercontrols/2290768#2290768I believe you have the wrong attribute name.
Aequitarum Custos
+1  A: 

Assuming you control the component (the A class), apply DesignerSerializationVisibilityAttribute to the expensive property, with the Hidden option to say "don't generate a setter for this property":

public class A : UserControl
{
  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  public int UpdateSetting 
  {
    // Write to database or some such thing
  }
}

(EDIT: On re-reading I'm not sure whether you want to prevent initialisation by the designer, or make it optional, or allow it to be done through the designer but defer the actual execution of the initialisation. This addresses only the first of those scenarios.)

itowlson
Yes, I was shooting for optional, but in retrospect this probably works too.
Nicholas