【问题标题】:How to enable design support in a custom control?如何在自定义控件中启用设计支持?
【发布时间】:2010-05-07 00:12:12
【问题描述】:

我将尝试解释我所追求的。我不知道它的技术术语,所以这里是:

示例 1: 如果我在表单上放置一个 ListView 并添加一些列,我可以在设计时单击并拖动这些列来调整它们的大小。

示例 2: 现在,我在 UserControl 中放置一个 ListView 并将其命名为“MyCustomListView”(也许添加一些方法以某种方式增强它)。

如果我现在将“MyCustomListView”放在表单上,​​我将无法单击并拖动列标题以在设计时调整它们的大小。

有什么方法可以轻松实现吗?某种形式的“将点击和拖动事件传递给底层控件,让该控件发挥它的魔力”。我并不是真的想重新编码,只需传递鼠标单击(或其他任何内容)并让 ListView 在这种情况下像上面第一个示例中那样做出反应。

【问题讨论】:

    标签: c# user-controls


    【解决方案1】:

    Windows 窗体设计器具有用于大多数控件的专用设计器类。 ListView 的设计器是 System.Windows.Forms.Design.ListViewDesigner,它是 System.Design.dll 程序集中的一个内部类。此类使您能够拖动列标题。

    UserControl 使用 System.Windows.Forms.Design.ControlDesigner 设计器类。它没有做任何特别的事情,只是在控件周围放置一个带有拖动手柄的矩形。您可以看到它的标题:在您将用户控件放在表单上之后,用于设计类的是 ControlDesigner,而不是 ListViewDesigner。因此,您将无法拖动列标题。另请注意,ControlDesigner 无法访问 UC 内部的控件。

    但是,通过创建您自己的设计师可以解决这个问题。从 Projects + Add Reference 开始,选择 System.Design。您需要向 UC 添加公共属性以公开列表视图并应用 [DesignerSerializationVisibility] 属性以允许保存更改的属性。并将 [Designer] 属性应用到 UC 类以替换默认设计器。一切都应该像这样(使用默认名称和显示“员工”的 ListView):

    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Windows.Forms.Design;   // Note: add reference required: System.Design.dll
    
    namespace WindowsFormsApplication1 {
        [Designer(typeof(MyDesigner))]   // Note: custom designer
        public partial class UserControl1 : UserControl {
            public UserControl1() {
                InitializeComponent();
            }
    
            // Note: property added
            [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
            public ListView Employees { get { return listView1; } }
        }
    
        // Note: custom designer class added
        class MyDesigner : ControlDesigner {
            public override void Initialize(IComponent comp) {
                base.Initialize(comp);
                var uc = (UserControl1)comp;
                EnableDesignMode(uc.Employees, "Employees");
            }
        }
    }
    

    用户控件中的列表视图现在可以正常单击和设计。

    【讨论】:

    • ++ 感谢您的好意。很高兴你出现并教会了我一些东西。
    • 这只是完美答案的完美示例 =) 谢谢!
    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多