Problem getting the IDesignerHost of a custom control in VS10 .NET form

血红的双手。 提交于 2021-02-10 06:52:27

问题


According to docs.microsoft.com, I'm trying to get my form's IDesignerHost in design time:

private static Form _findForm;
protected override void OnCreateControl()
{
    if (_findForm == null) { _findForm = FindForm(); }
    if (_findForm == null) { throw new Exception("FindForm() returns null."); }

    // NullReference
    //IDesignerHost dh = (IDesignerHost)_findForm.Site.GetService(typeof(IDesignerHost));
    IDesignerHost dh = (IDesignerHost)GetService(typeof(IDesignerHost));
    Console.WriteLine(dh == null); // true
    // ...
}

But as you see I can't get a ref. Do I need a ": IDesigner" class or is the OnCreateControl call to early to get a valid reference?

Update: About the link in comments:

public override ISite Site
{
    get { return base.Site; }
    set
    {
        Console.WriteLine("Site set"); // Never happens
        base.Site = value;
        if (value == null) { return; }
    }
}

and

Console.WriteLine(Site == null); // true

I tried also events after everything is initialized. Nothing seems to help/work.

So how the heck I can get the IDesignerHost? 😩


回答1:


Final Update:

The accepted solution of the question is totally the opposite and wrong:

public override ISite Site
{
    get { return base.Site; }
    set
    {
        base.Site = value;
        if (value == null) { return; }
        IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
        if (host != null)
        {
            IComponent componentHost = host.RootComponent;
            if (componentHost is ContainerControl) { ContainerControl = componentHost as ContainerControl; }
        }
    }
}

It should be the getter like this:

private IDesignerHost _host;
public override ISite Site
{
    get
    {
        if (base.Site != null)
        {
            IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
            if (host != null) { _host = host; }
        }
        return base.Site;
    }
    set { base.Site = value; }
}

As I found out, the getter is triggered until it can finally create a valid reference.

base.Site //null
base.Site //null
base.Site //null
base.Site //null
base.Site //...
base.Site //finally got a reference - time to grab it! ;)


来源:https://stackoverflow.com/questions/64579197/problem-getting-the-idesignerhost-of-a-custom-control-in-vs10-net-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!