列表框项上下文菜单仅当选择了“列表框多个项”时

本文关键字:列表 上下文 菜单 选择 | 更新日期: 2023-09-27 18:35:40

当没有或只选择一个项目时,如何禁用列表框项上下文菜单?

ListBox 具有 SelectedItems 属性,但它是只读的,您无法绑定到它。

<ListBox ItemsSource="{Binding Items}" SelectionMode="Extended">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="GOGO" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
                <TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

列表框项上下文菜单仅当选择了“列表框多个项”时

这应该有效:

<ListBox ItemsSource="{Binding Items}" SelectionMode="Extended">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="GOGO" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" Value="0">
                    <Setter Property="ContextMenu" Value="{x:Null}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" Value="1">
                    <Setter Property="ContextMenu" Value="{x:Null}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

添加两个DataTrigger检查SelectedItems.Count是 0 还是 1,在这种情况下,它将ContextMenu设置为 {x:Null}