Google Search

Sunday, March 29, 2009

Creating customizable WPF drop-down menus (1)

In this series of articles I'll explain the process of creating a drop-down menu that can be customized using drag-and-drop.

Enough preface, now on to the job!

Step 1: A simple drop-down menu

A simple drop down menu can be built in WPF using the Menu and MenuItem classes. This can be done is XAML of course, and would look like this:
    <MenuItem Header = "MenuItem1">
        <MenuItem Header = "MenuItem1.1"/>
        <MenuItem Header = "MenuItem1.2"/>
        <Separator Margin = "0,0,0,0" Height = "Auto"/>
        <MenuItem Header = "MenuItem1.3">
            <MenuItem Header = "MenuItem1.3.1"/>
        <MenuItem Header = "MenuItem1.4">
            <MenuItem Header = "MenuItem1.4.1"/>
    <MenuItem Header = "MenuItem2"/>
    <MenuItem Header = "MenuItem3" HorizontalAlignment = "Right">
        <MenuItem Header = "MenuItem3.1"/>
        <MenuItem Header = "MenuItem3.2"/>
        <Separator Margin = "0,0,0,0"/>
        <MenuItem Header = "MenuItem3.3">
            <MenuItem Header = "MenuItem3.3.1"/>
This menu, however, cannot be customized using Drag-and-Drop by the end-user at runtime. In order to do that, we need to implement a dragging mechanism.

Fortunately, WPF has a built-in Drag-and-Drop assistance class, that does the hard parts for us. All we need to do is to detect when we want to begin dragging, then pass it on to the Drag-and-Drop helper. Oh, and we also need to handle the drop :-)

Important Note:
The MenuItem class is limited in its behavior. In order to prepare to some of the more advanced steps, I'll need to inherit MenuItem to my own class, that will allow me to do the needed operations.
I'll call this class DraggableMenuItem, and let it implement internally everything the draggable menu items does.

No comments:

Post a Comment