我如何禁用列表框的选择?


当前回答

IsEnabled = false

其他回答

我发现了一个非常简单和直接的解决方法,我希望它也适用于你

<ListBox ItemsSource="{Items}">
    <ListBox.ItemContainerStyle>
       <Style TargetType="{x:Type ListBoxItem}">
           <Setter Property="Focusable" Value="False"/>
       </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

IsEnabled = false

这也将工作,如果我有需要使用列表框而不是itemscontrol,但只是显示不应该是可选的项目,我使用:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="IsHitTestVisible" Value="False" />
    </Style>
</ListBox.ItemContainerStyle>

方法1 -项目控制

除非你需要ListBox的其他方面,你可以使用ItemsControl代替。它将项目放在ItemsPanel中,没有选择的概念。

<ItemsControl ItemsSource="{Binding MyItems}" />

默认情况下,ItemsControl不支持其子元素的虚拟化。如果你有很多项,虚拟化可以减少内存使用和提高性能,在这种情况下,你可以使用方法2和样式ListBox,或添加虚拟化到你的ItemsControl。

方法2 -样式化列表框

或者,只是样式ListBox这样选择是不可见的。

<ListBox.Resources>
  <Style TargetType="ListBoxItem">
    <Style.Resources>
      <!-- SelectedItem with focus -->
      <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                       Color="Transparent" />
      <!-- SelectedItem without focus -->
      <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                       Color="Transparent" />
      <!-- SelectedItem text foreground -->
      <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}"
                       Color="Black" />
    </Style.Resources>
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
  </Style>
</ListBox.Resources>

这里的答案很好,但我想要一些稍微不同的东西:我想要选择,但只是不希望它被显示(或在不同的事情中显示)。

上面的解决方案对我(完全)不起作用,所以我做了其他的事情:我为我的列表框使用了一种新的样式,它完全重新定义了模板:

<Style x:Key="PlainListBoxStyle" TargetType="ListBox">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <ContentPresenter />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <ItemsPresenter/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

从那开始,你可以很容易地添加你自己的选择高亮,或者让它像这样,如果你不想要任何。