0

I have a TreeView for which I am trying to make a ContextMenu. The ContextMenu needs to have a couple of static MenuItems: "test" and "test." It should also have a list of MenuItems within a MenuItem that presents the user with a list of dynamically loaded options (Binding to Parent.Parent.Children).

I can't figure out how to combine a DataTemplate with static MenuItems. This is my best attempt:

<TreeView x:Name="SpatialHierarchyTree" DataContext="{Binding topContainer}" ItemsSource="{Binding Project}" >
<TreeView.Resources>
    <ContextMenu x:Key="moveContext" StaysOpen="True" ItemsSource="{Binding Parent.Parent.Children}">
        <MenuItem Header="Test"/>
        <MenuItem Header="Test"/>
        <MenuItem Header="List">
            <ContextMenu.ItemTemplate>
                <DataTemplate>
                    <MenuItem Header="{Binding Name}"  CommandParameter="{Binding Name}" Click="MenuItem_Click"/>
                </DataTemplate>
            </ContextMenu.ItemTemplate>
        <MenuItem/>
    </ContextMenu>
</TreeView.Resources>
</TreeView>

Is there a way to achieve this?

Ryan Daley
  • 15
  • 6
  • 1
    bind ItemsSource only on MenuItem: `` ? – ASh Nov 08 '22 at 10:23
  • also https://stackoverflow.com/questions/14489112/how-do-i-dynamically-bind-and-statically-add-menuitems – ASh Nov 08 '22 at 10:24
  • @ASh, your solution of ItemsSource on the MenuItem throws an error "InvalidOperationException: Cyclic reference found while evaluating the ThemeStyle property on element 'System.Windows.Controls.TextBlock'." – Ryan Daley Nov 08 '22 at 11:39
  • no idea what you are talking about; but as the one who has all the code in IDE, you can investigate – ASh Nov 08 '22 at 11:58

1 Answers1

1

You could use a CompositeCollection, e.g.:

<ContextMenu ...>
    <ContextMenu.Resources>
        <CollectionViewSource x:Key="cvs" Source="{Binding Parent.Parent.Children}" />
    </ContextMenu.Resources>
    <ContextMenu.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={StaticResource cvs}}" />
            <MenuItem Header="Test"/>
            <MenuItem Header="List"/>
        </CompositeCollection>
    </ContextMenu.ItemsSource>
</ContextMenu>
mm8
  • 163,881
  • 10
  • 57
  • 88