MenuItems#

In Windows Forms, you can only add strings to be displayed in a menu. It would be a lot easier if you could add entire objects to a MenuItem, which could override their ToString()-method to determine the way to represent them in the menu item. For instance, you may want to map menu items to objects so that when the menu item is clicked, you immediately get the correct object in the event handler's sender object. Now, there is no way to associate an object with a menu item.

As a solution, you could consider subclassing the MenuItem class and adding a Tag property that can contain any Object. It is impossible to override the Text property of the MenuItem class so you must set the Text property to the tag object's ToString() value at construction or when the Tag property changes. Now when you listen for the Click event of the MenuItem, cast the sender to your MenuItem subclass and obtain the associated object through the Tag property.

Code sample for a generic MenuItem class with a Tag property:

public class TaggedMenuItem : System.Windows.Forms.MenuItem
{
    private object _tag;
    public object Tag
    {
        get { return _tag; }
    }
    public TaggedMenuItem( object tag )
    {
        _tag = tag;
        if( tag != null ) this.Text = tag.ToString();
    }
}

Of course you can do a whole lot more with this kind of subclassing but this can serve as an easy start...

Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In