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


当前回答

也许你只需要ItemsControl的功能?它不允许选择:

<ItemsControl ItemsSource="{Binding Prop1}" ItemTemplate="{StaticResource DataItemsTemplate}" />

其他回答

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

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

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

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

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

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

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

解决方案应该简单直接。

这个方法有几个优点:

键盘导航也被禁用。这不是IsFocusable, IsHitTestVisible等的情况。 没有“禁用”元素的视觉提示:只有ListBoxItem是禁用的,但TextBlock。前景色属性设置正确的颜色。

结果:无法通过键盘或鼠标选择项目,颜色也不是“灰色”,因为我们没有禁用整个控件。

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsEnabled" Value="False" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" Foreground="Black" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>