wpfxamlwpf-controlsmaterial-design-in-xaml

How to remove padding on the left and top of MenuItem.Icon?


I am using .Net 8.0 in my WPF project and also MaterialDesign. My problem is that I want to create a Menu where the root MenuItem has a plus icon, but for some reason trying to create an icon the size of my entire MenuIten it crawls down due to Margin (or Padding). Here is some XAML code with my Menu:

<Border Grid.Column="1" Grid.ColumnSpan="5"
        Grid.Row="1" Padding="30 10">
    <StackPanel Orientation="Horizontal">
        <Menu Width="45" Height="45" Style="{StaticResource ActionItemsMenuStyle}"
              Padding="0" Margin="0">
            <MenuItem Background="White" Height="45">
                <MenuItem.Icon>
                    <materialDesign:PackIcon Kind="Plus"/>
                </MenuItem.Icon>
            </MenuItem>
        </Menu>
    </StackPanel>
</Border>

I tried changing the height and width of "<materialDesign:PackIcon Kind="Plus"/>" but it had no effect. Changing the Template MenuItem seemed to me a rather cumbersome solution for such a problem. I'd be happy to get any answers!

EDIT: Resource "ActionItemsMenuStyle" is empty not worry


Solution

  • The problem is that the built-in control template for MenuItem has a fixed size for the icon. You can change this by overriding the control's template, but that might be overkill for your use case. If that ends up being the direction you need to go, though, check out this answer: https://stackoverflow.com/a/35328211/15534202

    The easiest thing to do to is put the icon in the header tag MenuItem.Header instead, as that can take any control. If the goal is having that one icon take up the entire space of the menu, this should get you there.

    xaml

    <Menu Width="45" Height="45">
        <!-- ADD Padding="0" to MenuItem -->
        <MenuItem Background="White" Height="45" Width="45" Padding="0">
            <!-- USE HEADER INSTEAD OF ICON -->
            <MenuItem.Header>
                <materialDesign:PackIcon Kind="Plus" Width="45" Height="45" />
            </MenuItem.Header>
        </MenuItem>
    </Menu>
    

    Result

    Result

    Adding submenus with this approach works fine as well
    <Menu Width="45" Height="45">
        <!-- ADD Padding="0" -->
        <MenuItem Background="White" Height="45" Width="45" Padding="0">
            <!-- USE HEADER INSTEAD OF ICON-->
            <MenuItem.Header>
                <materialDesign:PackIcon Kind="Plus" Width="45" Height="45" />
            </MenuItem.Header>
            <MenuItem Header="Item 1" />
            <MenuItem Header="Item 2" />
            <MenuItem Header="Item 3" />
        </MenuItem>
    </Menu>
    

    Result with submenus