Custom Property Default Value & .NET Designer

2019-08-17 06:32发布

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
  }
}

2条回答
来,给爷笑一个
2楼-- · 2019-08-17 06:52
[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.

查看更多
我只想做你的唯一
3楼-- · 2019-08-17 07:08

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.)

查看更多
登录 后发表回答