3

我很难让它工作,而且我对需要使用的所有模板感到绝望。这是情况。

我想要一个动态创建的菜单。该代码获取对象列表,对列表进行分组,然后设置菜单的 itemsource。

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy(Function(p) p.GroupName)

我需要有关 XAML 中的模板和数据绑定的帮助。我希望发生的是创建一个菜单,其中顶部项目是组键,然后每个键的子项是项目本身。

然后我需要为每个孩子设置一个点击处理程序,以便我可以在菜单项点击时执行代码。

事实证明,这对我来说很难完成。有人可以提供一个 XAML 示例来说明这将如何工作吗?

4

1 回答 1

2

经过一些实验和一点运气,我终于找到了解决方案。我希望这可以帮助其他人解决这个问题。回顾一下,我想绑定到具有子(可能是孙子)的数据源(分组),并动态构建菜单。挑战是将所有菜单项单击事件路由到单个事件处理程序。这就是我想出的。

<!-- Common handler for ALL menu items. This was a tough one to figure out since I kept thinking this had to be done the template somehow -->
    <Menu MenuItem.Click="navView_Click" >
        <Menu.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding}">
                <!-- Content presenter for the list of IGrouping objects. Binding is done to the Key property on the IGrouping class -->
                <ContentPresenter Content="{Binding Path=Key}"></ContentPresenter>
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <!-- Content presenter for the list of objects in each grouping. Binding is done to the Name property on the custom class -->
                        <ContentPresenter Content="{Binding Path=Name}"></ContentPresenter>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu> 

这是代码中设置的 itemsource。C#和VB分别

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy(Function(p) p.GroupName)

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy( p => p.GroupName);
于 2012-03-22T16:23:58.880 回答