HierarchicalDataTemplate.ItemTemplate中的水平拉伸WPF ContextMenu MenuItem

时间:2018-02-03 12:29:35

标签: wpf xaml mvvm contextmenu

我有一个WPF系统托盘应用程序。右键单击托盘栏图标时,ContextMenu使用HierarchicalDataTemplate获得2级动态填充菜单。它可以工作,但可点击"第二级上的部分项目未正确拉伸到父控件的可用宽度。相反见图:

Picture of menu where 2nd level items dont fill the parent control

现在,用户必须单击MenuItem的较暗部分(文本所在位置)才能执行此项目的Command。我希望整个菜单行能够触发Command

这是我的XAML:

<CollectionViewSource x:Key="Items" Source="{Binding Path=Items}" />
<ContextMenu x:Shared="false" x:Key="Menu" HorizontalContentAlignment="Stretch">
    <ContextMenu.ItemTemplate>
        <HierarchicalDataTemplate DataType="SystemTrayItemsViewModel" ItemsSource="{Binding Items}">
            <StackPanel Orientation="Horizontal">
            <Image Source="{Binding Converter={StaticResource TabIconConverter}}" />
            <TextBlock Text="{Binding Name}" />
            </StackPanel>
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <MenuItem Header="{Binding Text}" ToolTip="{Binding ToolTip}" Command="{Binding ToClipBoardCommand}" HorizontalContentAlignment="Stretch" />
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </ContextMenu.ItemTemplate>
    <ContextMenu.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={StaticResource Items}}">
            </CollectionContainer>
            <Separator />
            <MenuItem Header="Exit" cal:Message.Attach="ExitApplication" />
        </CompositeCollection>
    </ContextMenu.ItemsSource>
</ContextMenu>

有关完整源代码,请查看https://github.com/kasperhlund/textgrunt

1 个答案:

答案 0 :(得分:0)

我刚刚在another SO question中找到了答案。

问题似乎是在MenuItem中指定了ItemTemplateContextMenu显然在MenuItem周围包裹了另一个ItemTemplate,引起了这种嵌套效果。相反,您必须通过MenuItem的{​​{1}}进行此操作:

Style