DotNetSpartan
DotNetSpartan

Reputation: 1001

How do i keep two different commands at menu item and sub menu item generated through HierarchicalDataTemplate wpf

In the below piece of code, nested menu's get generated from an observable collection called CollectionOfAuthors. I've placed two commands, One at the 'ToplevelMenuItem' and another for submenu item (through textblock.InputBindings). Though the command for submenuitem is working, I am unable to hit the command for the TopLevelMenuItem:

Need to understand what extra i need to do ?

<MenuItem x:Name="TopLevelMenuItem" Header="Authors" ItemsSource="{Binding CollectionOfAuthors}"  Command="{Binding DataContext.RefreshAuthorsList, RelativeSource={RelativeSource AncestorType=Menu}}"     >
    <MenuItem.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Books}">
            <TextBlock Text="{Binding AuthorName}"/>
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding BookName}" >
                                    <TextBlock.InputBindings>
                                                        <MouseBinding Command="{Binding DataContext.NavigateToBook, RelativeSource={RelativeSource AncestorType=Menu}}"  MouseAction="LeftClick" />                                                                                                                  
                                   </TextBlock.InputBindings>
                    </TextBlock>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </MenuItem.ItemTemplate>
</MenuItem>

Upvotes: 0

Views: 164

Answers (1)

sTrenat
sTrenat

Reputation: 1049

Try with

<MenuItem x:Name="TopLevelMenuItem" Header="Authors" ItemsSource="{Binding CollectionOfAuthors}" >
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="SubmenuOpened">
      <i:InvokeCommandAction Command="{Binding DataContext.RefreshAuthorsList}"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>

If you want to prevent from firing command from submenues you will need to pass {Binding .} to command, and if param is not type of your ViewModel, then don't fire your action.

Also, you need to add reference to System.Windows.Interactivity and xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" in your xaml header

Upvotes: 1

Related Questions