在设计时不要在某些属性中“设置”

时间:2011-03-25 13:16:39

标签: c#

为什么在设计时不工作在我的code.but属性字体中设置“dataGrid”属性,工作正确。 我在表格上使用了这个组件。(我用设计时间测试来测试它)

enter code here 
namespace Example
{
  public partial class Component1 : System.Windows.Forms.DataGridView
  {

    public Component1()
    {
    }

    private DataGridViewColumn _gridcolumn;

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [TypeConverter(typeof ( ExpandableObjectConverter))]
    public DataGridViewColumn gridcolumn
    {
        get
        {
            if (_gridcolumn == null)
                _gridcolumn = new DataGridViewColumn();
            return _gridcolumn;
        }

        set                                                 //Do not Work Set in designTime 
        {
            _gridcolumn = value;
        }
    }


    private System.Drawing.Font _MyFont;
    public System.Drawing.Font MyFont
    {
        get
        {
            if (_MyFont == null)
                _MyFont = new System.Drawing.Font("tahoma", 8);
            return _MyFont;
        }
        set
        {
            _MyFont = value;                                            //Work correctly in design time
        }
    }

    int _with;
    public int withcustom
    {
        get
        {
            return _with;
        }
        set
        {
            _with = value;                                           //Work correctly in design time
        }
    }

}

}

2 个答案:

答案 0 :(得分:4)

短版

从您的媒体资源中删除DesignerSerializationVisibility(DesignerSerializationVisibility.Content),或将其更改为DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)

长版

DesignerSerializationVisibility(DesignerSerializationVisibility.Content)应用于您的属性意味着WinForms设计器不会生成设置属性值的代码,而是生成该属性值的属性值的代码。

例如,假设我有以下两种类型:

public class MyControl : Control
{
    public class MyControlProperties
    { 
        public string Prop1 { get; set; }
        public int Prop2 { get; set; }
    }

    private MyControlProperties props;

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public MyControlProperties Properties
    {
        get
        {
            if(props == null) props = new MyControlProperties();

            return props;
        }
    }
}

当设计人员在表单上生成MyControl的代码时,它看起来像这样:

myControl.Properties.Prop1 = "foo";
myControl.Properties.Prop2 = 10;

因此,不是设置Properties属性的值(在此代码中,它是只读的;虽然它不是),但通常这样的属性是),它在该属性的上设置属性的值。

答案 1 :(得分:0)

这是一个很好的例子:

public partial class SCon : UserControl
    {
        public SCon()
        {
            InitializeComponent();
            if (Persoanas == null)
            {
                Persoanas = new List<Persoana>();
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<Persoan> Persoanas { get; set; }

    }

    [Serializable]
    public class Persoan   
    {
        public int Id { get; set; }
        public String Name { get; set; }
    }