Manually un/checking additional component menu items

unhandled

(Jose Luis Garcia del Castillo) #1

This question is about, how can I manually manage the un/checking of additional ToolStripMenuItems on a component, without binding a variable to the item?

Let’s say my component has an internal variable

bool foo = true;

which I want to toggle on the right-click menu by adding an item. My question is, why does this work:

        bool foo = true;

        protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
        {
            base.AppendAdditionalComponentMenuItems(menu);

            var fooToggle = Menu_AppendItem(menu, "Foo Toggle", FooHandler, true, this.foo);
            fooToggle.ToolTipText = "Desc text";
        }

        protected void FooHandler(object sender, EventArgs e)
        {
            this.foo = !this.foo;
            this.Message = this.foo.ToString();
            this.ExpireSolution(true);
        }

But this doesn’t?

        bool foo = true;

        protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
        {
            base.AppendAdditionalComponentMenuItems(menu);

            var fooToggle = Menu_AppendItem(menu, "Foo Toggle", FooHandler, true, true);
            fooToggle.ToolTipText = "Desc text";
        }

        protected void FooHandler(object sender, EventArgs e)
        {
            var item = sender as ToolStripMenuItem;
            item.Checked = !item.Checked;  // manually un/check the item
            this.foo = item.Checked;  // manage the value myself
            this.Message = this.foo.ToString();
            this.ExpireSolution(true);
        }

(David Rutten) #2

Sooo, the item is always checked regardless of the value of foo. Then in the handler you always uncheck it because item.Checked = !item.Checked;, and then you set foo to false.

As far as I understand, this means that foo is true, up until you click on the menu item once after which it will always be false. That doesn’t sound like the logic you were hoping to code.

I will say that there is no point in changing the menu item from within the handler. The menu item will be discarded very soon and disappear into the black hole that is the garbage collector. The next time the menu opens an entirely new menu item will be created for the duration of the menu. Changing the state of one menu item will not carry over to the next.


(Jose Luis Garcia del Castillo) #3

Ooooh, I see. So, AppendAdditionalComponentMenuItems is invoked every time the user right-clicks on the component, hence generating a new item list with checks determined from whichever parameters at that time? I don’t know why I thought it was some form of variable binding…
Thanks!


(David Rutten) #4

Yes indeed. I guess this differs sufficiently from the way the Form Designer works in Visual Studio that it is confusing.