码迷,mamicode.com
首页 > 其他好文 > 详细

Prevent Adding Component More than once

时间:2015-02-05 10:44:18      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

Question: I‘m developing a C# component, I want to prevent the user from adding this component to the Form if the Form already has an instance of the component.

Answer: You can create a custom ComponentDesigner for your component, override its InitializeNewComponent() method to judge wether there‘s already an instance existes, if so, just return from this method. I write the following sample for your information:
[Designer(typeof(myComponentDesigner))]
class myComponent : Component
{
    public myComponent(IContainer container)
    {
        // Add object to container‘s list so that
        // we get notified when the container goes away
        container.Add(this);
    }
}

class myComponentDesigner : ComponentDesigner
{
    public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
    {
        IDesignerHost service = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
        if (service == null) return;
        ComponentCollection cc = service.Container.Components;

        int count = 0;
        foreach (Component c in cc)
        {
            if (c.GetType() == this.Component.GetType() )
            {
                count++;
                if (count > 1)
                {
                    service.Container.Remove(this.Component);
                    MessageBox.Show(
                       "You cannot add more than one instance of the myComponet!");
                    return;
                }
            }
        }

        base.InitializeNewComponent(defaultValues);
    }
}
 

Prevent Adding Component More than once

标签:

原文地址:http://www.cnblogs.com/eastson/p/4273953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!