Injecting a MenuStripItem to a derived class from the base constructor

心不动则不痛 提交于 2019-12-11 05:36:22

问题


I want to inject a MenuStrip Item or create a new one if it doesn't exists (but this is a different question) from the base constructor, the logic is the following:

public class LocalizedForm : Form 
{
    public LocalizedForm() 
    {
        Shown += (sender, e) =>
        {
            MenuStrip menu = null;
            if (HasValidMenu(out menu))
                LanguageManager.AttachMenu(menu); //Language Manager will inject MenuStripItems to the passed MenuStrip
        };
    }

    protected bool HasValidMenu(out MenuStrip menu)
    {
        try
        {
            menu = Controls.OfType<MenuStrip>().SingleOrDefault(x => x.Dock == DockStyle.Top);
            return menu != null;
        }
        catch
        {
            menu = null;
            return false;
        }
    }
}

and two childs:

public partial class frmMain : LocalizedForm 
{

}

public partial class frmCredentials : LocalizedForm 
{

}

Why I use Shown event? That's because the MenuStrip will not be found in the Controls until it is rendered or loaded.

Well, my main problem now is that the menu options are created twice instead one time.

As you can see there:

By this reason I have changed the following things:

protected bool HasValidMenu(out MenuStrip menu) to protected bool HasValidMenu(string name, out MenuStrip menu)

The call has been changed to:

if (HasValidMenu(out menu)) to if (HasValidMenu(GetType().Name, out menu))

This will return the main type name from where this was called.

And the magic:

menu = Controls.OfType<MenuStrip>().SingleOrDefault(x => x.Dock == DockStyle.Top); to

menu = Application.OpenForms[name].Controls.OfType<MenuStrip>().SingleOrDefault(x => x.Dock == DockStyle.Top);

But for some reason, Shown event doesn't affect to derived classes. I have testing by calling the Load or Shown event of derived classes by using Application.OpenForms[name] but this is also null.

So, what can I do?

来源:https://stackoverflow.com/questions/46017882/injecting-a-menustripitem-to-a-derived-class-from-the-base-constructor

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