【问题标题】:From a usercontrol code-behind, in design mode, how do I get all the controls names contained in the parent?在设计模式下,如何从用户控件代码隐藏中获取父控件中包含的所有控件名称?
【发布时间】:2011-04-26 03:43:31
【问题描述】:

使用 WinForms 我正在编写一个组件用户控件,我希望它能够显示一个设计器编辑器表单,我可以在其中看到组件所在表单上所有控件名称的列表。

我得到了组件用户控件的基本机制和设计器编辑器的支持。我的问题与此无关。

假设我有一个表单,在 IDE 中,我将组件放置在组件托盘中,并将其他几个控件放置在表单上。现在,我调用组件的设计器编辑器并显示控件名称列表。

这是一段代码:

internal class MyComponentEditor : UITypeEditor
{
    public override object EditValue
    (
        ITypeDescriptorContext context,
        IServiceProvider provider, object value
    )
    {
        var instance = context.Instance as MyComponent;
        var container = instance.Container;
        var controls = container.Components.Cast<Control>;
        var names = controls.Select (x => x.Name);
    }
}

这里,names 变量应该包含所有控件的名称,但我只得到类型名称!

必须是显而易见的东西... ;)

【问题讨论】:

  • 是否有像var names = controls.Select (x =&gt; x.ID); 这样的 ID 属性。假设你想要的就是你想要的“名字”?
  • 不,没有 ID 属性。

标签: c# winforms user-controls


【解决方案1】:

好的,我搞定了。

对于每个控件,您需要执行以下操作来获取控件的名称:

(string)TypeDescriptor.GetProperties (control)["Name"].GetValue (control)

从我的例子:

var names = controls.Select (x => (string)TypeDescriptor
                                      .GetProperties(x)["Name"]
                                      .GetValue(x));

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2012-08-29
    • 2021-12-23
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多