wpfdata-binding

How to add list of MenuItem controls using MVVM binding?


I'm trying to render an MRU files menu item list using MVVM and data binding. However, I'm not able to …

  1. assign an access key
  2. assign a mnemonic
  3. assign a command

This is the code I'm using:

<MenuItem x:Name="FileMenu_MruList" Visibility="{Binding Path=FileMruList.Count, Converter={x:Static conv:VisibilityCounterConverter.Instance}}">
  <MenuItem.Resources>
    <cmd:FileMruCommand x:Key="FileMruCmd"/>
    <CollectionViewSource x:Key="MruFiles" Source="{Binding Path=FileMruList}"/>
  </MenuItem.Resources>

  <MenuItem.CommandBindings>
    <CommandBinding Command="{StaticResource ResourceKey=FileMruCmd}" Executed="FileMruItem_Executed"/>
  </MenuItem.CommandBindings>

  <MenuItem.ItemsSource>
    <CompositeCollection>
      <CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=MruFiles}}"/>
      <Separator/>
      <MenuItem Header="_Delete list"/>
    </CompositeCollection>
  </MenuItem.ItemsSource>

  <MenuItem.ItemTemplate>
    <HierarchicalDataTemplate DataType="{x:Type mru:MruItem}">
      <TextBlock Text="{Binding Converter={x:Static conv:MruItemConverter.Instance}}"/>
    </HierarchicalDataTemplate>
  </MenuItem.ItemTemplate>
</MenuItem>

From the following screenshot you can see:

File MRU menu list

… that

  1. The numbers are not underlined. The underscore character is output vanilla.
  2. Pressing any of the assigned numbers while the menu items are active won't execute them.

How can I have these menu items act as expected?


Solution

  • In the future, please post enough information to fully understand and reproduce the problem. Otherwise, instead of solving the problem, we have to guess what you actually meant.

    If I understood your code correctly, you have a collection "FileMruList" whose objects are converted by the converter "conv:MruItemConverter.Instance" into a string of the type "_1 Test a". This string is passed to the property "TextBlock.Text". The TextBlock itself is in the content template MenuItem.

    From this solution, you expect behavior similar to <MenuItem Header="_1 Test a"/>.

    Did I understand you correctly?

    If yes, then in your case I think it will be enough for you to replace TextBlock with AccessText:

      <MenuItem.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type mru:MruItem}">
          <AccessText Text="{Binding Converter={x:Static conv:MruItemConverter.Instance}}"/>
        </HierarchicalDataTemplate>
      </MenuItem.ItemTemplate>
    </MenuItem>