【问题标题】:Custom control properties for an internal TextBox内部文本框的自定义控件属性
【发布时间】:2012-11-03 05:13:56
【问题描述】:

考虑一个具有属性 Rows 的自定义控件:

private EMRow[] _rows;

public CustControl()
{
    InitializeComponent();
}

public EMRow[] Rows
{
    get
    {
        return _rows;
    }
    set
    {
        _rows = value;
    }
}

每个 EMRow 创建一个 TextBox 并公开两个属性,一个用于 Text,一个用于控件本身:

private TextBox _txtValue;

public EMRow()
{
    if (_txtValue == null)
        _txtValue = new TextBox();
}

public string Value
{
    get
    {
        return _txtValue.Text;
    }
    set
    {
        _txtValue.Text = value;
    }
}

public TextBox ValueTextBox
{
    get
    {
        return _txtValue;
    }
    set
    {
        _txtValue = value;
    }
}

如果您将此自定义控件拖放到表单上并修改 Value 属性,它会更新并保护对 Designer.cs 文件的更改。

当您深入研究 ValueTextBox 属性(同样,所有这些都在 Visual Studio Designer 中,而不是代码中)并修改属性时,更改不会保存到 Designer.cs 文件中。就设计者而言,甚至没有创建和引用此属性的 TextBox 对象。

我确定这是“预期的”行为,但我不知道为什么。我在这里缺少 VS 设计师的基础吗?

【问题讨论】:

    标签: c# winforms visual-studio-2012 custom-controls designer


    【解决方案1】:

    经过一番挖掘,我找到了解决这个问题的方法,告诉设计者通过添加 DesignerSerializationVisibility 属性来序列化这个对象本身

    private TextBox _txtValue;
    
    public EMRow()
    {
        if (_txtValue == null)
            _txtValue = new TextBox();
    }
    
    public string Value
    {
        get
        {
            return _txtValue.Text;
        }
        set
        {
            _txtValue.Text = value;
        }
    }
    
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public TextBox ValueTextBox
    {
        get
        {
            return _txtValue;
        }
        set
        {
            _txtValue = value;
        }
    }    
    

    Winforms Designer: Modify (and keep) properties in sub objects 谢谢汉斯!

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2014-06-11
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多