创建分层ContextMenu动态MVVM

时间:2017-07-11 03:01:15

标签: c# wpf mvvm contextmenu

我想从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>();
}

在视图中:

<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>

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

enter image description here

我已经检查了输出窗口以检查绑定,所有绑定都有效,没有例外。

请帮我找出原因,提前谢谢!

1 个答案:

答案 0 :(得分:3)

您应该定义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>