ListBoxItem ContextMenu仅在选中ListBox多个项目时

时间:2016-02-22 18:22:50

标签: c# wpf xaml

如果没有选择或只选择一个项目,如何禁用listboxitem上下文菜单?

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>

1 个答案:

答案 0 :(得分:6)

这应该有效:

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