Someone recently posted an article to CodeProject which provides a pretty nice implementation of a “split button.” WPF does not have a built-in split button, so this is a solid addition to the standard control library. The original article can be found here.
The author of SplitButton allows you, the developer, to easily populate its ContextMenu by adding child MenuItem elements to the SplitButton in XAML. That looks something like so:
Using this “manual” approach is fine for many scenarios, but won’t help in others. It is not unusual to populate a menu with items that come from an XML file; like a config file just for that menu. This blog post shows how to bind the SplitButton’s dropdown menu to some XML data.
Here is the XML data we will use to populate the SplitButton’s menu:
Eventually we want the SplitButton’s menu to look like this:
We can accomplish this by configuring the SplitButton’s ContextMenu to use the XML data as a source for generating its items. This works because SplitButtons uses its ContextMenu as the dropdown shown when you click on the “dropdown button.” Here is the complete declaration of our bound SplitButton:
The SplitButton’s ContextMenu is configured in four ways.
- Its ItemsSource is bound to the XML data seen previously. This means that the MenuItems will be created automatically based on the XML data to which it is bound.
- The routed Click event of MenuItem is handled by the ContextMenu, so that when the user clicks on any of its MenuItems the same OnXmlMenuItemClick handler in the code-behind will be called.
- Its ItemContainerStyle is set to a Style which assigns the command’s ID to the Tag of the MenuItem. The “command” in this sense represents whatever action should occur when the item is clicked, and its ID is used in the code-behind to figure out what to do when an item is clicked.
- Its ItemTemplate is set to a DataTemplate which displays the command’s title. This is what you see when you look at a menu item in the dropdown.
The method in the Window’s code-behind, which executes when an item in the SplitButton’s ContextMenu is clicked, is defined like this:
Download the demo app here: Bound SplitButton (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress it. NOTE: This demo project, which I took from the CodeProject article, was built using a beta of Visual Studio 2008. All modifications were made to the Window1.xaml and Window1.xaml.cs files in the Demo project.