如何在WPF中使用DataSource从菜单中获取菜单项

时间:2018-11-30 05:18:41

标签: c# wpf data-binding menuitem

我有这样的XML菜单:

<MenuItem x:Name="MenuItemCameras" Header="Cameras" ItemsSource="{Binding LocalCameras}" >
<MenuItem.ItemTemplate>
 <DataTemplate>
<MenuItem Header="{Binding DisplayName}" IsCheckable="True" IsChecked="{Binding IsStreamingVideo}" IsEnabled="{Binding CanStreamVideo}" 
                    Command="{Binding DataContext.CommandSelectLocalCamera, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                    Click="MenuItemCameras_OnClick"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>

我要这样迭代:

foreach (MenuItem mMenuItem in MenuItemCameras) {
   //some code
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

要获取相应的MenuItem,您可以这样做

foreach (var item in MenuItemCameras.Items) {
    MenuItem menuItem = (MenuItem)MenuItemCameras.ItemContainerGenerator.ContainerFromItem(item);
    //some code
}

但是有一个缺点,只要未创建相应的MenuItem ItemContainerGenerator.ContainerFromItem就会返回null