WPF:模板化列表框项中的上下文菜单(InvalidCastException)

WPF: ContextMenu in templated ListBox Item (InvalidCastException)

我正在尝试向 ListBoxItem 添加上下文菜单。我正在使用 ListBox.ItemTemplate 和 DataTemplate(带有网格)来定义项目的布局,并为 ListBoxItem 设置样式。

在搜索中应该是这样:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <MenuItem Header="Rename" Click="Rename_Click" />
                </ContextMenu>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

但这会引发 XamlParseException/InvalidCastException 说法

Couldn't cast an object of the type
System.Windows.Controls.MenuItem to the type
System.Windows.Controls.Grid

我尝试将上下文菜单添加到 ItemTemplate 中的网格,但只有当您单击网格中的一个元素时它才有效(有一些空的 space)(或者,如果我向网格添加背景,但这会覆盖/"covers" 项目本身的悬停和选定样式)

搜索也找不到类似的问题,也想不通Exception的逻辑..

您可以通过将 ContextMenu 定义为资源来解决此问题:

    <ListBox>
        <ListBox.Resources>
            <ContextMenu x:Key="cm">
                <MenuItem Header="Rename" Click="Rename_Click" />
            </ContextMenu>
        </ListBox.Resources>
        <ListBox.ItemTemplate>
            ...
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="ContextMenu" Value="{StaticResource cm}" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

使用TargetType="ListBoxItem"串代码。因为编码语言需要知道List Box!