C# usercontrol how to access all child controls

好久不见. 提交于 2019-12-22 08:37:58

问题


I defined a custom panel with a table layout panel inside. However when I used this control on a winform I do not have access to the table layout panel properties. (I want for instance add a column or dock an other control in a cell). I try to changed the modifier property to public, but it still does not work. What can I do in order to see and change the panel layout properties ?

In fact, the question can be more generic : how to access/modify/move controls contained in a custom usercontrol ?

Thx


回答1:


You need to expose the properties you want to modify in your user control. For example, to change the column count property of the table layout control, from your user control, you have to expose the ColumnCount property:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public int ColumnCount
    { 
        get
        {
            return this.tableLayoutPanel1.ColumnCount;
        }

        set
        {
            this.tableLayoutPanel1.ColumnCount = value;
        }
    }
}

You can also then start to use some attributes to control how your user control is displayed in Visual Studio, for example, the above can be modified like so:

[DefaultProperty("ColumnCount")]
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    [Description("Gets or sets the column count of the table layout.")]
    [Category("TableLayout")]
    [DefaultValue(2)]
    public int ColumnCount
    { 
        get
        {
            return this.tableLayoutPanel1.ColumnCount;
        }

        set
        {
            this.tableLayoutPanel1.ColumnCount = value;
        }
    }
}

This sets the default property of the entire user control to "ColumnCount", and gives the column count property a description, a default value of 2, and sets in what category it should be displayed in the designer's properties window. There is a lot more that can do with a user control to add design time support.



来源:https://stackoverflow.com/questions/1346533/c-sharp-usercontrol-how-to-access-all-child-controls

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