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


当前回答

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

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

其他回答

我提出另一种解决办法。简单地重新模板ListBoxItem只不过是一个ContentPresenter,就像这样…

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

我采用这种方法的原因如下:

In my case, I don't want to disable user interaction with the contents of my ListBoxItems so the solution to set IsEnabled won't work for me. The other solution that attempts to re-style the ListBoxItem by overriding the color-related properties only works for those instances where you're sure the template uses those properties. That's fine for default styles, but breaks with custom styles. The solutions that use an ItemsControl breaks too many other things as the ItemsControl has a completely different look than a standard ListBox and doesn't support virtualization, meaning you have to re-template the ItemsPanel anyway.

上述内容不会改变ListBox的默认外观,不会禁用ListBox数据模板中的项,默认支持虚拟化,并且独立于应用程序中可能使用或不使用的任何样式。这就是KISS原则。

IsEnabled = false

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

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

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

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

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

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

你可以在你的列表框上面放置一个文本块,它不会改变你的应用程序的外观,也不允许选择任何项目。