开发者

How to add a menuItem to a context menu which has a set ItemsSource and ItemContainerStyle in XAML

开发者 https://www.devze.com 2023-04-08 13:01 出处:网络
I have the following XAML code. The contents in the ItemsSource are displayed as MenuItems. <controls:DropDownButton x:Name=\"btnOwner\"

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号