Horizontal Menu with Horizontal SubMenu in WPF

2019-04-02 08:22发布

I have been struggling with the WPF Menu and I simply cannot achieve what I want to.

I tried changing default styling on the Menu and MenuItem control, but this turned out terrible. I then tried styling it by making use of control templates, however, I think I came to realization that my WPF skill just aren't there yet.

Here is a picture of my desired result:

enter image description here

Is there anyone that can maybe point me in the right direction? Or maybe assist me with some xaml that will give my desired result?

1条回答
Luminary・发光体
2楼-- · 2019-04-02 09:06

You can set ItemsPanel with horizontal orientation, like this:

<Menu.ItemsPanel>
    <ItemsPanelTemplate>
        <VirtualizingStackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
</Menu.ItemsPanel>

Because both Menu and MenuItem are derived from ItemsControl.

Full example:

<Menu Width="100" 
        Height="30"
        Margin="10" 
        VerticalAlignment="Top"
        HorizontalAlignment="Left"
        Background="White"
        BorderBrush="Blue" 
        BorderThickness="1">

    <Menu.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </Menu.ItemsPanel>

    <MenuItem Header="_ITEM1">
        <MenuItem.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </MenuItem.ItemsPanel>

        <MenuItem Header="_SUBMENU1" IsCheckable="true"/>
        <MenuItem Header="_SUBMENU2" IsCheckable="true"/>
        <MenuItem Header="_SUBMENU3" IsCheckable="true"/>

        <Separator/>
    </MenuItem>

    <MenuItem Header="_ITEM2">
        <MenuItem Header="Undo"/>
        <MenuItem Header="Redo"/>
        <Separator/>
        <MenuItem Header="Cut"/>
        <MenuItem Header="Copy"/>
        <MenuItem Header="Paste"/>
    </MenuItem>            
</Menu>

Output

enter image description here

查看更多
登录 后发表回答