我想根据ViewModel中的数据动态创建Hierarchical ContextMenu。

在ViewMode中,我定义了ContextMenuAction:

public class ContextMenuAction : ViewModelBase
{
    public string Header { get; set; }
    public ICommand Action { get; set; }
    public Brush Icon { get; set; }
    public ObservableCollection<ContextMenuAction> SubActions { get; set; } = new ObservableCollection<ContextMenuAction>();
}

在 View 中:
<ContextMenu ItemsSource="{Binding Path=PlacementTarget.Tag.Actions, RelativeSource={RelativeSource Self}}">
<ContextMenu.ItemTemplate >
    <DataTemplate DataType="MenuItem">
        <MenuItem/>
    </DataTemplate>
</ContextMenu.ItemTemplate>

<ContextMenu.ItemContainerStyle>
    <Style TargetType="MenuItem">
        <Setter Property="ItemsSource" Value="{Binding SubActions}"/>
        <Setter Property="Header" Value="{Binding Header}" />
        <Setter Property="Command" Value="{Binding Action}"/>
    </Style>
</ContextMenu.ItemContainerStyle>

结果是,上下文菜单中没有文本。

c# - 动态创建分层ContextMenu MVVM-LMLPHP

我已经检查了输出窗口以检查绑定(bind),所有绑定(bind)都正常工作,没有异常(exception)。

请帮助我找出原因,在此先感谢!

最佳答案

您应该定义一个HierarchicalDataTemplate:

<ContextMenu ItemsSource="{Binding Path=PlacementTarget.Tag.Actions, RelativeSource={RelativeSource Self}}">
    <ContextMenu.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:ContextMenuAction}" ItemsSource="{Binding SubActions}">
            <TextBlock Text="{Binding Header}" />
        </HierarchicalDataTemplate>
    </ContextMenu.ItemTemplate>
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding Action}"/>
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>

关于c# - 动态创建分层ContextMenu MVVM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45024658/

10-11 13:02