Home > Software engineering >  TextBlock inside MenuItem does not became gray if MenuItem is Disabled
TextBlock inside MenuItem does not became gray if MenuItem is Disabled

Time:09-02

If I use this code:

<MenuItem x:Name="MenuSave" Header="Save" IsEnabled="False"/>

when MenuSave is disabled (in real code by a RoutedUICommand programmatically), the Header is disabled and text is gray.

But if I need more text like here:

<MenuItem x:Name="MenuSaveAs" IsEnabled="False">
     <MenuItem.Header >
            <StackPanel Orientation="Horizontal">
                   <TextBlock Text="Save as"/>
                   <TextBlock> ...</TextBlock>
            </StackPanel>
     </MenuItem.Header>
</MenuItem>

In this case, the Header is disabled but text is not gray.

How can I obtain text gray with composite text?

This is just simplified code to explain the problem, the real code is combination of translated terms.

CodePudding user response:

If you add the TextBlock thorough a HeaderTemplate, the color will be applied for the disabled state. By the way, you can use multiple Runs instead, so the same TextBlock is populated. If you bind a data item as Header, you can bind its properties in the template to the Runs.

<MenuItem x:Name="MenuSaveAs" IsEnabled="False">
   <MenuItem.HeaderTemplate>
      <DataTemplate>
         <TextBlock>
            <Run Text="Save as"/>
            <Run> ...</Run>
         </TextBlock>
      </DataTemplate>
   </MenuItem.HeaderTemplate>
</MenuItem>

Alternatively, if you need to format a string with a bound property, use HeaderStringFormat.

<MenuItem x:Name="MenuSaveAs"
          IsEnabled="False"
          Header="{Binding NameOfTheSavedItem}"
          HeaderStringFormat="Save as {0}...">

CodePudding user response:

I found an other easy way:

<MenuItem x:Name="MenuSaveAs" IsEnabled="False">
<MenuItem.Header >
    <StackPanel Orientation="Horizontal">
        <Label Padding="0" Content="Save as"/>
        <Label Padding="0" Content="..."/>
    </StackPanel>
</MenuItem.Header>
  • Related