Apply MenuItem.ItemContainerStyle without a Parent MenuItem

765 Views Asked by At

I have the following bit of XAML that works just fine, in that it produces a Recent Files menu item and a sub menu item for each Recent File:

<MenuItem Header="Recent Files" ItemsSource="{Binding RecentFiles}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding Open}" />
            <Setter Property="Header" Value="{Binding Name}" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>

This is within the File Menu and produces a menu structure something like this:

File
  New
  Open
  Save
  Save As
  --
  Recent Files
    File 1
    File 2
    File 3

Hopefully you get the idea...BUT really I do not want the parent MenuItem of Recent Files, I want the recent files to just be on the end of the File menu, more like this:

File
  New
  Open
  Save
  Save As
  --
  File 1
  File 2
  File 3

How might I achieve this? Is there a 'dummy' container element I might place around my MenuItem.ItemContainerStyle instead of the Recent Files MenuItem or should I be doing this in an altogether different way?

Thanks

Stuart

1

There are 1 best solutions below

0
On

Maybe you could use the CompositeCollection class to achieve what you want, and you need to add a CollectionViewSource to expose the RecentFiles to the CollectionContainer:

<Menu>
    <Menu.Resources>
        <CollectionViewSource x:Key="RecentFilesCvs" Source="{Binding RecentFiles}" />
    </Menu.Resources>
    <MenuItem Header="File">
        <MenuItem.ItemsSource>
            <CompositeCollection>
                <MenuItem Header="New"/>
                <MenuItem Header="Open"/>
                <MenuItem Header="Save"/>
                <MenuItem Header="Save As"/>
                <Separator/>
                <CollectionContainer Collection="{Binding Source={StaticResource RecentFilesCvs}"/>
            </CompositeCollection>
        </MenuItem.ItemsSource>
    </MenuItem>
</Menu>