I have a static resource defined as follows:
<ContextMenu x:Key="TestContextMenu" DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
<MenuItem Command="ApplicationCommands.Cut"/>
<!--<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Command="ApplicationCommands.Cut"/>
</CompositeCollection>
</ContextMenu.ItemsSource>-->
</ContextMenu>
My application works fine like this. However, I want to be able to add extra items to the context menu. So instead of adding menu items I want to use a CompositeCollection and then I run into binding issues. I minimized the problem and ended up with this. When I comment the MenuItem and uncomment the ContextMenu.ItemSource I get this error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
If the datacontext is correct in the first situation why is it not correct anymore in the second situation?
Edit: I don't want to add items to the contextmenu dynamically. I want to use this contextmenu as kind of a 'base context menu' providing cut/copy and paste from a composite collection resource. In some places I want more than just these three and there I could use a custom context menu that use that same collection combined with those extra items. Just to clarify this is the xaml I have in mind, but I cut the problem down to the simpler piece above.
<CompositeCollection x:Key="TreeViewItemContextMenuItems">
<MenuItem Command="ApplicationCommands.Cut" CommandTarget="{Binding}"/>
<MenuItem Command="ApplicationCommands.Copy" CommandParameter="{Binding}"/>
<MenuItem Command="ApplicationCommands.Paste" CommandParameter="{Binding}"/>
<Separator/>
<MenuItem Command="ApplicationCommands.Delete" CommandParameter="{Binding}"/>
</CompositeCollection>
<ContextMenu x:Key="TreeViewItemContextMenu" DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
<ContextMenu.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{StaticResource TreeViewItemContextMenuItems}" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>