wpf - 将样式添加到 HierarchicalDataTemplate 生成的 MenuItems

标签 wpf xaml datatemplate hierarchicaldatatemplate

我正在使用 HierarchicalDataTemplate 将分层数据添加到菜单控件。

<HierarchicalDataTemplate DataType="{x:Type local:MyType}" ItemsSource="{Binding Path=SubItems}">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/>
    </StackPanel>
</HierarchicalDataTemplate>

我的菜单是这样创建的

<Menu>
    <MenuItem ItemsSource="{Binding MyCollection}" Header="MainItem"></MenuItem>
</Menu>

如何向这些生成的菜单项添加样式以设置 IsCheckable例如属性(property)。重要的是,主 MenuItem(此处名为“MainItem”的 header )不应用此样式,因此它不可检查。

我使用 <Style> 尝试了多种方法和<DataTemplate但没有成功。

最佳答案

像这样:

<Menu>
    <Menu.ItemContainerStyle>
        <Style TargetType="MenuItem">
           ....
        </Style>
    </Menu.ItemContainerStyle>
</Menu>

或者在你的情况下:

<Menu>  
    <MenuItem Header="Text" ItemsSource="{Binding Data}" ItemContainerStyle="{SomeStyle}"/>  
</Menu>  

关于wpf - 将样式添加到 HierarchicalDataTemplate 生成的 MenuItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1439416/

相关文章:

c# - 您可以让扩展器覆盖 WPF 中的其他可视化树元素吗?

c# - 我应该以哪种方式定义资源字典以保持我的代码干净?

c# - 了解 OpacityMask 的有效区域

允许函数评估的 JavaScript 模板

c# - WPF重用XAML资源

wpf - 如何在文本框上实现自动保存?

c# - "ReflectionOnlyAssemblyResolve event"的 Visual Studio 构建问题

xaml - Xamarin 标题栏文本居中(跨平台)

DataTemplate 中的 WPF 命令绑定(bind)

wpf - 如何绑定(bind)到字典中的项目?