Custom Property Default Value & .NET Designer

馋奶兔 提交于 2020-01-06 08:22:18

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/2234417/custom-property-default-value-net-designer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!