代码之家  ›  专栏  ›  技术社区  ›  DotNetSpartan

如何在通过HierarchicalDataTemplate WPF生成的菜单项和子菜单项中保留两个不同的命令

  •  0
  • DotNetSpartan  · 技术社区  · 8 年前

    在下面的代码中,嵌套菜单是从一个名为collectionofauthors的可观察集合生成的。我放置了两个命令,一个位于“TopLevelMinItem”,另一个用于子菜单项(通过textBlock.inputBindings)。 虽然SubmenuItem的命令正在运行,但无法点击TopLevelMenuItem的命令:

    需要了解我还需要做什么?

    <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>
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   sTrenat    8 年前

    尝试用

    <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>
    

    如果要防止从子菜单中触发命令,则需要通过 {Binding .} 命令,如果param不是ViewModel的类型,则不要启动操作。

    此外,还需要添加对System.Windows.Interactivity和 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 在XAML标题中