如何在ListBox中禁用选择?
如何在ListBox中禁用选择?
<ListBox SelectionChanged="ListBox_SelectionChanged">
并且在代码后台:
private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
(sender as ListBox).SelectedItem = null;
}
这个方案有几个优点:
IsFocusable
、IsHitTestVisible
等情况下并非如此。ListBoxItem
被禁用,但是TextBlock.Foreground
属性设置了正确的颜色。结果:一个项目不能通过键盘或鼠标选择,并且颜色不是“灰色”,因为我们没有禁用整个控件。
<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>
对我来说,最好的解决方案是:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="True"/>
<Setter Property="IsHitTestVisible" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
注意:此解决方案不会禁用键盘导航或右键单击选择(即箭头键后跟空格键)
所有先前的答案要么完全删除选择功能(无法在运行时切换),要么仅删除视觉效果,但不删除选择。
但是,如果您想通过代码选择并显示选择,而不是通过用户输入选择呢?也许您想在不禁用整个列表框的情况下“冻结”用户的选择?
解决方案是将整个ItemsContentTemplate包装到没有视觉chrome的按钮中。按钮的大小必须等于项目的大小,因此它完全被覆盖。 现在使用按钮的IsEnabled属性:
启用按钮以“冻结”项目的选择状态。这是有效的,因为启用的按钮在鼠标事件冒泡到ListboxItem-Eventhandler之前吞噬了所有鼠标事件。您的ItemsDataTemplate仍将接收MouseEvents,因为它是按钮内容的一部分。
禁用按钮以启用通过单击更改选择。
<Style x:Key="LedCT" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Button IsEnabled="{Binding IsSelectable, Converter={StaticResource BoolOppositeConverter}}" Template="{DynamicResource InvisibleButton}">
<ContentPresenter />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="InvisibleButton" TargetType="{x:Type Button}">
<ContentPresenter/>
</ControlTemplate>
dartrax
ListItem item = new ListItem(yourvalue, yourkey);
item.Attributes.Add("disabled","disabled");
lb1.Items.Add(item);
IsEnabled = false