How to add a menuItem to a context menu which has a set ItemsSource and ItemContainerStyle in XAML
I have the following XAML code. The contents in the ItemsSource are displayed as 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.Con开发者_如何学Pythontent>
<controls:DropDownButton.DropDown>
<ContextMenu HorizontalContentAlignment="Stretch"
ItemsSource="{Binding Owners, Mode = TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemContainerStyle="{StaticResource OwnerStyle}">
</ContextMenu>
</controls:DropDownButton.DropDown>
How can I add a new menuItem something like a SubMenuHeader via XAML to this List?
It will create itself. All that you need to provide the ItemTemplate
in which you will decide what to show and how to show in each MenuItem
. Otherwise, the default implemention will call ToString()
method for each item in Owners
, and will display it in MenuItem
.
<ContextMenu ItemsSource="{Binding Owners}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
Here, I assumed that the type of owner has a property name Title
. For example, if Owners
is ObservableCollection<Owner>
, then Owner
is defined as:
public class Owner
{
public string Title { get; set;}
//...
}
That is basic idea as to how to use ItemTemplate
. Now if you want submenuitem in the context menu, then you've to use HierarchicalDataTemplate
instead of DataTemplate
in the ItemTemplate
definition.
精彩评论