WPF MenuItem child controls width is less than parent menuitem

1k views Asked by At

As shown in below code, The contextmenu has four menuitems one, two, three and four. MenuItem three has subitems embeded in list box and they are test1, test2 and test3. The width of test1 test2 and test3 is less than parent item (i.e menuitem or submenuitem). How to make the width stretched to takethe width of the parent.

<Window.Resources>

    <ContextMenu x:Key="CustomContextMenu">
        <MenuItem Header="One"></MenuItem>
        <MenuItem Header="two"></MenuItem>
        <MenuItem Header="three" Margin="0"  x:Name="menu_three" 
                  Padding="0" 
                  Grid.IsSharedSizeScope="True" >
            <StackPanel  Background="Blue" Margin="0" 
                         Width="{Binding Path=PlacementTarget.Parent.Width, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}">
                <ListBox HorizontalAlignment="Stretch">
                    <ListBoxItem Content="test1"></ListBoxItem>
                    <ListBoxItem Content="test2"></ListBoxItem>
                    <ListBoxItem Content="test3"></ListBoxItem>
                </ListBox>
            </StackPanel>
        </MenuItem>
        <MenuItem Header="four"></MenuItem>
    </ContextMenu>

</Window.Resources>

Thanks

1

There are 1 answers

5
Nitesh On

Remove ListBox and use MenuItem to show your sub menu items

<ContextMenu>
    <MenuItem Header="One"></MenuItem>
    <MenuItem Header="two"></MenuItem> 
    <MenuItem Header="three" Margin="0"  x:Name="menu_three" Padding="0" >
       <MenuItem Header="test1"></MenuItem>
       <MenuItem Header="test2"></MenuItem>
       <MenuItem Header="test3"></MenuItem>
    </MenuItem>
    <MenuItem Header="four"></MenuItem>
</ContextMenu>