【问题标题】:Update parent control when the child control is manually removed in the designer在设计器中手动删除子控件时更新父控件
【发布时间】:2013-08-19 02:25:02
【问题描述】:

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

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


我进行了设置,以便在集合编辑器中添加或删除 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); 
            });
    }
}

【问题讨论】:

  • 您可能只需要刷新设备。处理对象添加和删除的代码是什么样的?
  • 嗨。我提到的问题只发生在任何部署之前的设计时。因此,刷新 Windows Mobile 6 设备将毫无用处。尽管如此,我还是在我的问题中编辑了一些源代码。
  • 将 [Browsable(false)] 属性应用于 Items 属性,使其不会显示在设计器中。让它可见是没有意义的,设计器已经支持添加和删除控件。
  • 如果我将其标记为 [Browsable(false)](在 CF 中,您必须在单独的 xmta 文件中执行此操作),那么显然“Items | (Collection)”条目将从属性列表中消失。但是这个属性对于在设计时将 ButtonListItems 添加到列表中是必不可少的。
  • 这不仅仅是将内容拖放到 ButtonList 控件上的问题。控件处理其 ButtonListItems 的定位和可能的格式化,就像 TabControl 处理其 TabPages 的定位和格式化一样。但要做到这一点,您必须使用“Items | (Collection)”属性。

标签: c# compact-framework design-time


【解决方案1】:

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

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

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

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

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

不幸的是,在 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));
        }
    }

    // ...
}

希望对使用紧凑框架的任何人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2012-01-15
    • 2015-10-03
    相关资源
    最近更新 更多