Creating a Most Recents Menu Item with the MenuStrip
The FileEventArgs class in my new EventArgs is my new event argument for the OpenFileCommand. It simply contains a FileName property, representing the return value from the OpenFileDialog. The OpenFileCommand contains an OpenFileDialog field. The constructor (Sub New) creates an instance of the OpenFileDialog and wires up the FileOK event.
The FileOK event handler raises an event to let external consumers, in this case the form, handle FileOK and it calls AddToRecents. AddToRecents checks to see whether you have indicated what menu is the recents menu by using a sentinel and dyanmically adds the indicated filename as the menu item name.
RecentsClick raises an event to the external consumer (the form again). The next two fields are event fields. Consumers need to attach to these two events. The code for doing this is shown in Listing 2. The next three properties represent some stuff I want to let the consumer configure, such as Title and Filter. And, the fourth property lets the consumer indicate the ToolStripMenuItem that represents the Recent Files menu.
Do is the only public method making the OpenFileCommand pretty easy to use. Call Do and it initializes the OpenFileDialog and shows it. If the user clicks OK, the FileOK behavior takes over. Undo is there for symmetry and it's a traditional part of the Command behavior pattern. Look at dofactory.com for a great elaboration on the Command pattern or check out my (much) earlier article on the Command pattern at Devx.com. (You can also learn how to incorporate patterns into all of your code by reading books like my recent book LINQ Unleashed for C#. I know you're VB programmers, but if you can program you can read C#.)
Elevating the quality of your product is knowing how to do relative simple things like adding dynamic menus and then encapsulating them so you don't have to do them again.
I recall about ten years ago doing some walkthroughs and people would argue about what is good code and what isn't. The subjectivity is somewhat mitigated now by this concept: good code has a high frequency and density of well-known patterns at least at a minimum. No patterns and...
About the Author
Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book LINQ Unleashed for C# now available on Amazon.com and fine bookstores everywhere. You may contact him for technology questions at firstname.lastname@example.org.
Copyright © 2008 By Paul T.Kimmel. All Rights Reserved.
Page 3 of 3