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


当前回答

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

其他回答

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

一个简单的修复工作在Windows Phone上,例如在选择设置选定项为空:

    <ListBox SelectionChanged="ListBox_SelectionChanged">

在后面的代码中:

    private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        (sender as ListBox).SelectedItem = null;
    }

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

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

另一个值得考虑的选项是禁用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控件模板。

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

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