如何在WPF中将数据绑定到IGrouping?

3

我发现这个很难使其正常工作,使用时需要涉及大量的模板,让我感到非常困惑。以下是情况介绍:

我想要动态创建一个菜单。代码会获取一个对象列表groups,对该列表进行分组,然后将结果设置为菜单的项源。

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

我需要帮助在XAML中进行模板化和数据绑定。我希望创建一个菜单,顶部项目是组键,然后每个键的子项是它们自己。

接下来,我需要为每个子项设置点击处理程序,以便在菜单项单击时执行代码。

这对我来说很难实现。有人能提供一个XAML示例,展示如何工作吗?

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> 

以下是C#和VB中设置itemsource的代码:

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

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy( p => p.GroupName);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接