C# usercontrol 如何访问所有子控件 [英] C# usercontrol how to access all child controls

查看:73
本文介绍了C# usercontrol 如何访问所有子控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个自定义面板,里面有一个表格布局面板.但是,当我在 winform 上使用此控件时,我无法访问表格布局面板属性.(例如,我想在单元格中添加一列或停靠其他控件).我尝试将修饰符属性更改为 public,但它仍然不起作用.我该怎么做才能查看和更改面板布局属性?

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 ?

谢谢

推荐答案

您需要在用户控件中公开要修改的属性.例如,要更改表格布局控件的列数属性,从您的用户控件中,您必须公开 ColumnCount 属性:

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

然后你也可以开始使用一些属性来控制你的用户控件在 Visual Studio 中的显示方式,例如,上面可以这样修改:

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

这将整个用户控件的默认属性设置为ColumnCount",并为列计数属性提供一个描述,默认值为 2,并设置它应该在设计器的属性窗口中显示的类别.用户控件还可以做很多事情来添加设计时支持.

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.

这篇关于C# usercontrol 如何访问所有子控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆