c# - C# 中的自定义 Windows 控件库

标签 c# custom-controls

如何在我自己的自定义 Windows 控件库中实现小任务功能,如下所示? alt text

最佳答案

您需要为您的控件创建自己的设计器。首先添加对 System.Design 的引用。示例控件可能如下所示:

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;

[Designer(typeof(MyControlDesigner))]
public class MyControl : Control {
    public bool Prop { get; set; }
}

注意 [Designer] 属性,它设置自定义控件设计器。要开始使用,请从 ControlDesigner 派生您自己的设计器。覆盖 ActionLists 属性以为设计器创建任务列表:

internal class MyControlDesigner : ControlDesigner {
    private DesignerActionListCollection actionLists;
    public override DesignerActionListCollection ActionLists {
        get {
            if (actionLists == null) {
                actionLists = new DesignerActionListCollection();
                actionLists.Add(new MyActionListItem(this));
            }
            return actionLists;
        }
    }
}

现在您需要创建您的自定义 ActionListItem,它可能如下所示:

internal class MyActionListItem : DesignerActionList {
    public MyActionListItem(ControlDesigner owner)
        : base(owner.Component) {
    }
    public override DesignerActionItemCollection GetSortedActionItems() {
        var items = new DesignerActionItemCollection();
        items.Add(new DesignerActionTextItem("Hello world", "Category1"));
        items.Add(new DesignerActionPropertyItem("Checked", "Sample checked item"));
        return items;
    }
    public bool Checked {
        get { return ((MyControl)base.Component).Prop; }
        set { ((MyControl)base.Component).Prop = value; }
    }
}

在 GetSortedActionItems 方法中构建列表是创建您自己的任务项面板的关键。

这是快乐的版本。我应该注意到,在处理此示例代码时,我将 Visual Studio 崩溃到桌面 3 次。 VS2008 能够应对自定义设计器代码中未处理的异常。经常保存。调试设计时代码需要启动另一个 VS 实例,该实例可以在出现设计时异常时停止调试器。

关于c# - C# 中的自定义 Windows 控件库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4186953/

相关文章:

ios - 如何在 iOS 中为 UITextView 添加两个输入附件 View ?

c# - 如何在Phone类库项目中添加ResourceDictionary并访问它

c# - 如何正确地将 PHP 和 CURL 帖子转换为 groupon API 的 C# HTTP 客户端帖子

binding - WinRT 自定义控件依赖属性设置/绑定(bind)

cocoa - 如何确保类似 NSSlider 的自定义控件的 KVO 行为正确?

php - 为什么实现 ArrayAccess、Iterator 和 Countable 的类不能使用 array_filter()?

c# - Moq - 模拟通用存储库

c# - 如何检查元素是否存在?

c# - 如何使用 C# 在列表框中列出类对象?

c# - 如何访问 System.Windows.Forms.Design.ParentControlDesigner?