如何将菜单项添加到具有设置ItemsSource和ItemContainerStyle的上下文菜单中
本文关键字:ItemContainerStyle ItemsSource 上下文 菜单 设置 菜单项 添加 | 更新日期: 2023-09-27 18:09:34
我有以下XAML代码。ItemsSource中的内容显示为MenuItems。
<controls:DropDownButton x:Name="btnOwner"
DockPanel.Dock="Left"
Style="{StaticResource btnStyle}"
HorizontalAlignment="Left"
Visibility="{Binding IsOwnerVisible}">
<controls:DropDownButton.Content>
<ContentControl Width="22"
Height="22"
Style="{StaticResource iconOwner}"/>
</controls:DropDownButton.Content>
<controls:DropDownButton.DropDown>
<ContextMenu HorizontalContentAlignment="Stretch"
ItemsSource="{Binding Owners, Mode = TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemContainerStyle="{StaticResource OwnerStyle}">
</ContextMenu>
</controls:DropDownButton.DropDown>
我如何通过XAML添加一个新的菜单项,比如SubMenuHeader到这个列表?
它会自动创建。提供ItemTemplate
所需的所有内容,您将决定在每个MenuItem
中显示什么以及如何显示。否则,默认实现将为Owners
中的每个项目调用ToString()
方法,并将其显示在MenuItem
中。
<ContextMenu ItemsSource="{Binding Owners}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
在这里,我假设所有者的类型有一个属性名称Title
。例如,如果Owners
为ObservableCollection<Owner>
,则Owner
定义为:
public class Owner
{
public string Title { get; set;}
//...
}
这是关于如何使用ItemTemplate
的基本思想。现在,如果你想在上下文菜单中使用submenuitem,那么你必须在ItemTemplate
定义中使用HierarchicalDataTemplate
而不是DataTemplate
。