如果我有一个命令列表,其中每个命令都有一个组号,我如何在上下文菜单中显示这些命令?
下面是我尝试过的代码,但我似乎无法显示子菜单项。
namespace groupTest
{
public class GroupedCommand
{
public string Name { get; set; }
public ICommand Command { get; set; }
public int Group { get; set; }
}
public partial class Window1 : Window
{
public List<GroupedCommand> Commands
{
get;
private set;
}
public Window1()
{
Commands = new List<GroupedCommand>();
Commands.Add(new GroupedCommand() { Name = "A", Group = 0 });
Commands.Add(new GroupedCommand() { Name = "B", Group = 0 });
Commands.Add(new GroupedCommand() { Name = "C", Group = 1 });
Commands.Add(new GroupedCommand() { Name = "D", Group = 1 });
var defView = (CollectionView)CollectionViewSource.GetDefaultView(Commands);
defView.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
DataContext = this;
InitializeComponent();
}
}
}
<Window x:Class="groupTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.ContextMenu>
<ContextMenu ItemsSource="{Binding Commands}">
<ContextMenu.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<MenuItem Header="{Binding}">
<ItemsPresenter />
</MenuItem>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ContextMenu.GroupStyle>
</ContextMenu>
</Window.ContextMenu>
</Window>