簡體   English   中英

如何在WPF中數據綁定到IGrouping?

[英]How do I databind to a IGrouping in WPF?

我很難將其付諸實踐,而且我無可救葯地與所有需要使用的模板混淆。 這是情況。

我想動態創建一個菜單。 代碼獲取對象列表,對列表進行分組 ,然后設置菜單的itemsource。

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

我需要XAML中的模板和數據綁定方面的幫助。 我希望發生的是創建一個菜單,其中頂部項目是組密鑰,然后每個密鑰的子項是項目本身。

然后我需要為每個孩子設置一個單擊處理程序,以便我可以在菜單項單擊上執行代碼。

事實證明,這對我來說很難實現。 有人可以提供一個XAML示例,說明這將如何工作?

經過一些實驗和一點點運氣后,我終於找到了解決方案。 我希望這可以幫助其他人解決這個問題。 回顧一下,我想綁定到一個數據源(已分組),它有子項(可能是孫子),並且動態構建菜單。 挑戰是將所有菜單項單擊事件路由到單個事件處理程序。 這就是我想出來的。

<!-- 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM