C
C
crescent2020-10-27 18:08:36
WPF
crescent, 2020-10-27 18:08:36

Set text instead of picture in MenuItem?

A normal MenuItem in wpf looks like this:

{image} | {text}
How can I insert text instead of an image?
For example, I want it to be like this:
101 Petrov
How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris the Animal, 2020-10-28
@crescent

You need to hover over the menu (MenuItem will be selected if the menu is not empty) and press the right mouse button, select EditTemplate -> Edit a copy. A style with templates will be created.
There you will see the following code

<ControlTemplate
    x:Key="{ComponentResourceKey ResourceId=SubmenuItemTemplateKey,
                    TypeInTargetAssembly={x:Type MenuItem}}">
<!-- Много кода -->
</ControlTemplate>

Look there
. This is the thing that displays the icon. As you can see, it displays what is set in the Icon property (see ContentSource ="Icon").
<ContentPresenter
    x:Name="Icon"
    Width="16"
    Height="16"
    Margin="3"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    ContentSource="Icon"
    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />

Set the Width property to a larger value. Margin on the left and / or right can be reduced if this is the norm by design.
As you can see, this ContentPresenter displays what is contained in the MenuItem's Icon property. Just set the desired text in the Icon.
The vertical bar in that template is
<Rectangle
    Width="1"
    Margin="29,2,0,2"
    HorizontalAlignment="Left"
    Fill="{StaticResource Menu.Static.Separator}" />

<Menu
    Grid.Row="0"
    Height="25"
    VerticalAlignment="Top"
    DockPanel.Dock="Top">
    <MenuItem Style="{StaticResource MenuItemStyle}" Header="Тесты">
        <MenuItem
            Icon="101"
            Command="{Binding WorkspaceViewModel.UpdateTestsCommand}"
            Header="Обновить список тестов"
            IsEnabled="{Binding Mode, Converter={StaticResource ApplicationModeEnumToBooleanConverter}, ConverterParameter='Tests'}" />
         <!-- -->
    </MenuItem>
    <MenuItem Header="Режим">
         <!-- -->
    </MenuItem>
</Menu>

5f999711c2b74120986977.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question