gpt4 book ai didi

c# - ListBoxItem ContextMenu 仅当 ListBox 选择多个项目时

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:11 25 4
gpt4 key购买 nike

当未选择任何项目或仅选择一个项目时,如何禁用列表框项目上下文菜单?

ListBox 有一个 SelectedItems 属性,但它是只读的,您不能绑定(bind)到它。

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

关于c# - ListBoxItem ContextMenu 仅当 ListBox 选择多个项目时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com