使WPF中的列表框项不可选

Gha*_*han 56 wpf listbox

我在WPF中有一个列表框,当他们选择一个项目时,它会显示一个难看的颜色我可以让所有的项目都不可选吗?

Tho*_*que 92

如果您不需要选择,请使用ItemsControl而不是aListBox

  • 并非总是如此; `ItemsControl`不能做一些人可能需要的`ListBox`,比如使用虚拟化时的`ScrollIntoView`. (18认同)
  • 不一定是真的.可能有很多原因不希望使用ListBox的*原始*选择机制但仍然保留功能:仅举一个例子,考虑一个ListBox图像,你想在每个图像的角落添加一个额外的复选框启用选择.您可以将此复选框连接到原始选择机制,仍然要禁用ListBox的原始单击选择. (3认同)

小智 29

在ListBoxItem样式中将Focusable属性添加为false:

<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
  <!-- Possibly other setters -->
  <Setter Property="Focusable" Value="False" />
</Style>
Run Code Online (Sandbox Code Playgroud)

  • 这才是真正的答案. (3认同)

4im*_*ble 14

如果您不希望它们可选择,那么您可能不想要列表视图.但如果这是你真正需要的,那么你可以用一种风格来做:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>


<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type ListBoxItem}">
        <Border 
          Name="Border"
          Padding="2"
          SnapsToDevicePixels="true">
          <ContentPresenter />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Border" Property="Background" Value="#DDDDDD"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground" Value="#888888"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

  </Page.Resources>
  <Grid>  
    <ListBox>
      <ListBoxItem>One</ListBoxItem>
      <ListBoxItem>Two</ListBoxItem>
      <ListBoxItem>Three</ListBoxItem>
    </ListBox>
  </Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)

查看IsSelected触发器.您可以将边框设置为不同的颜色,使其不是"丑陋"或将其设置为透明,并且在选中时将不可见.

希望这可以帮助.

  • 添加**<Setter Property ="FocusVisualStyle"Value ="{x:Null}"/>**以消除焦点矩形. (3认同)

Asa*_*ani 13

请在列表框中使用此内容.我发现这个非常优雅的解决方案

<ListBox ItemsSource="{Binding YourCollection}">
    <ListBox.ItemContainerStyle>
       <Style TargetType="{x:Type ListBoxItem}">
           <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
Run Code Online (Sandbox Code Playgroud)


Den*_*per 5

有一个更简单的方法:set ListBoxproperty IsHitTestVisible="False"。这样可以防止列表中的所有项目接收鼠标事件。这样做的好处是,当您将鼠标悬停在上方时,也可以停止突出显示。

它在WP 7.1中对我有用。

  • 但是整个列表框都没有响应。包括滚动条。 (2认同)