2012-03-21 60 views
3

我很難得到這個工作,並且我無法理解所有需要使用的模板。這是情況。如何將數據綁定到WPF中的IGrouping?

我想要一個動態創建的菜單。代碼取對象列表,列表,然後設置菜單的項目源。

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

我需要XAML中的模板和數據綁定幫助。我希望發生的事情是創建一個菜單,首選項是組鍵,然後每個鍵的子項都是項目本身。

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

這證明對我來說很難完成。有人可以提供一個XAML的例子來說明這將如何工作?

回答

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); 
相關問題