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


当前回答

方法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>

其他回答

方法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>

要禁用列表框/下拉菜单中的一个或多个选项,您可以添加“disabled”属性,如下所示。这阻止用户选择这个选项,它得到一个灰色的覆盖。

ListItem item = new ListItem(yourvalue, yourkey);
item.Attributes.Add("disabled","disabled");
lb1.Items.Add(item);

你可以切换到使用ItemsControl而不是ListBox。ItemsControl没有选择的概念,所以没有什么可以关闭的。

对我来说,最好的解决办法是:

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

另一个值得考虑的选项是禁用ListBoxItems。这可以通过设置ItemContainerStyle来完成,如下面的代码片段所示。

<ListBox ItemsSource="{Binding YourCollection}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsEnabled" Value="False" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

如果你不希望文本是灰色的,你可以通过添加一个画笔到样式的资源来指定禁用的颜色,使用以下键:{x:Static SystemColors.GrayTextBrushKey}。另一种解决方案是重写ListBoxItem控件模板。