我有以下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的新menuItem?
答案 0 :(得分:0)
它会创造自己。您需要提供ItemTemplate
所需的全部内容,您将在其中决定要展示的内容以及如何在每个MenuItem
中展示。否则,默认实施将为ToString()
中的每个项目调用Owners
方法,并将其显示在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
的基本想法。现在,如果您想在上下文菜单中使用子菜单,那么您必须在DataTemplate
定义中使用HierarchicalDataTemplate
而不是ItemTemplate
。