1

我正在使用 C# 中的 Compact Framework 3.5 为 Windows Mobile 6 设备编写自定义控件。我正在编写的控件代表一个按钮列表,我们称之为ButtonList和按钮ButtonListItem

ButtonListItem 的列表可以在设计器中通过集合编辑器进行编辑:

Visual Studio 设计器项目集合

我对其进行了设置,以便在集合编辑器中添加或删除 ButtonListItem 时更新和重新绘制 ButtonList。

这是问题所在:

当我通过用鼠标选择它并在设计器中按下删除按钮手动删除 ButtonListItem 时,ButtonList 的内部状态不会更新。

我的目标是使设计器中的手动删除行为类似于集合编辑器中的删除。

一个例子是 TabControl 类,其中在集合编辑器中删除标签页和手动删除的行为完全相同。

您将如何实现这一目标?


编辑 1:用于向 ButtonList 添加和删除 ButtonListItem 的简化代码

class ButtonList : ContainerControl
{        
    public ButtonListItemCollection Items { get; private set; } // Implements IList and has events for adding and removing items

    public ButtonList()
    {
        this.Items.ItemAdded += new EventHandler<ButtonListItemEventArgs>(
            delegate(object sender, ButtonListItemEventArgs e)
            {
                // Set position of e.Item, do more stuff with e.Item ...

                this.Controls.Add(e.Item);   
            });

        this.Items.ItemRemoved += new EventHandler<ButtonListItemEventArgs>(
            delegate(object sender, ButtonListItemEventArgs e)
            {
                this.Controls.Remove(e.Item); 
            });
    }
}
4

1 回答 1

0

总结一下,我找到了解决问题的方法。像 TabControl 一样,我的 ButtonList 包含两个集合:

  1. ControlCollection 继承自 Control 类
  2. ButtonListItemCollection(TabControl 有 TabPageCollection)

添加 ButtonListItems 是通过属性中的集合编辑器完成的。删除可以在集合编辑器中完成,也可以通过在设计器中选择 ButtonListItem 并按键盘上的DEL按钮(手动删除)来完成。

使用集合编辑器时,ButtonListItems 被添加到/从 ButtonListItemCollection 中添加/删除,然后添加到/从 ControlCollection 中删除。

但是,当手动删除 ButtonListItem 时,它只会从 ControlCollection 中删除,而不是从 ButtonListItemCollection 中删除。所以需要做的是检测 ButtonListItemCollection 何时持有不在 ControlCollection 中的 ButtonListItems。

不幸的是,在 Compact Framework 中,Control 类中没有 ControlRemoved 事件。因此,一种解决方案如下所示:

class ButtonList : ContainerControl
{
    // ...

    public ButtonListItemCollection Items { get; private set; }

    protected override void OnPaint(PaintEventArgs pe)
    {
        if (this.Site.DesignMode)
        {
            this.Items.RemoveAll(x => !this.Controls.Contains(x));
        }
    }

    // ...
}

希望这可以帮助任何使用紧凑框架的人。

于 2013-08-17T14:28:34.050 回答