ToolStripDropDownButton equivalent in WPF?

2019-07-23 19:30发布

问题:

I'm very newbie to the WPF technology. I've been developing in WinForms for around 6 years.

Now I would like to advance one big step in my skills by learning WPF. I'm reading the introduction guides in MSDN, while as a personal exercise I'm trying to translate the sructure of a WinForms UI to its WPF UI equivalent.

This is a simple mockup of the WinForms controls structure that I would like to reproduce in WPF:

My problem is trying to reproduce the equivalent control/behavior for the ToolStripDropDownButton control.

In the Windows Forms Controls and Equivalent WPF Controls article, Microsoft just says that the equivalent control for a ToolStripDropDownButton is a ToolBar...with composition. I don't understand at all what it means about "with composition". I've been reading and experimenting with the Toolbar, but I didn't found the way to add a dropdown button thing inside the toolbar.

My question: someone could guide me or show me a brief example of how can I add a drop down button thing inside a Toolbar?.

回答1:

You can put a Menu in Toolbar. A Menu contains some MenuItem. Each MenuItem has a Header which is it's content and can be a text or other elements. Also each MenuItem can have some nested or MenuItems. For example, to have a menu structure like this:

You can use such code:

<ToolBar>
    <Menu Background="#00000000">
        <MenuItem >
            <MenuItem.Header>
                <StackPanel Orientation="Horizontal">
                    <TextBlock>Menu 1</TextBlock>
                    <Path VerticalAlignment="Center" Margin="8,2,0,0"
                          Fill="Black" Data="M 0 0 L 3 3 L 6 0 Z"/>
                </StackPanel>
            </MenuItem.Header>
            <MenuItem Header="Menu 1-1" >
                <MenuItem Header="Menu 1-1-1"/>
                <MenuItem Header="Menu 1-1-2"/>
            </MenuItem>
            <MenuItem Header="Menu 1-2"/>
            <MenuItem>
                <MenuItem.Header><TextBox Width="100"/></MenuItem.Header>
            </MenuItem>
            <MenuItem>
                <MenuItem.Header><DatePicker Width="100"/></MenuItem.Header>
            </MenuItem>
        </MenuItem>
        <MenuItem >
            <MenuItem.Header>
                <StackPanel Orientation="Horizontal">
                    <TextBlock>Menu 2</TextBlock>
                    <Path VerticalAlignment="Center" Margin="8,2,0,0" 
                          Fill="Black" Data="M 0 0 L 3 3 L 6 0 Z"/>
                </StackPanel>
            </MenuItem.Header>
            <MenuItem Header="Menu 2-1"/>
            <MenuItem Header="Menu 2-2"/>
            <MenuItem Header="Menu 2-3"/>
        </MenuItem>
        <MenuItem Header="Menu 3"/>
    </Menu>
</ToolBar>