【问题标题】:Horizontal stretch WPF ContextMenu MenuItem in HierarchicalDataTemplate.ItemTemplateHierarchicalDataTemplate.ItemTemplate 中的水平拉伸 WPF ContextMenu MenuItem
【发布时间】:2018-07-13 19:43:20
【问题描述】:

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

现在用户必须单击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

【问题讨论】:

  • 您找到解决此问题的方法了吗?我也遇到了这个问题,但 HierarchicalDataTemplate 没有。该问题与使用 CompositeCollection 绑定 VM 的集合以及 xaml 定义的 MenuItems 有关。

标签: wpf xaml mvvm contextmenu


【解决方案1】:

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

似乎问题在于在ItemTemplate 中指定MenuItemContextMenu 显然将另一个MenuItem 包裹在ItemTemplate 周围,从而导致了这种嵌套效果。相反,您必须通过MenuItemStyle 来执行此操作:

<ContextMenu>
   <ContextMenu.Resources>
      <Style TargetType="{x:Type MenuItem}">
         <Setter Property="Header" Value="{Binding Text}"/>
         <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
         <Setter Property="Command" Value="{Binding ToClipBoardCommand}"/>
         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      </Style>
   </ContextMenu.Resources>
</ContextMenu>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多