WPF ListBox可以为"只读"吗?
时间:2020-03-06 15:00:45 来源:igfitidea点击:
我们有一个场景,我们要显示项目列表并指出哪个是"当前"项目(带有小箭头标记或者更改的背景色)。
ItemsControl对我们不利,因为我们需要" SelectedItem"的上下文。但是,我们希望以编程方式移动选择,并且不允许用户更改选择。
有没有一种简单的方法可以使ListBox不交互式?我们可以通过故意吞下鼠标和键盘事件来弄虚作假,但是我是否缺少一些基本属性(例如将" IsEnabled"设置为false而不影响其视觉样式)来满足我们的需求?
还是...还有另一个WPF控件兼具SelectedSelect属性的ItemsControl呢?
解决方案
ItemsControl / ListBox是数据绑定的吗?
我只是在想,我们可以使每个项目的背景画笔都与源数据中的某个属性绑定,或者将该属性传递给转换器。就像是:
<ItemsControl DataContext="{Binding Source={StaticResource Things}}" ItemsSource="{Binding}" Margin="0"> <ItemsControl.Resources> <local:SelectedConverter x:Key="conv"/> </ItemsControl.Resources> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <local:Control Background="{Binding Path=IsSelected, Converter={StaticResource conv}}"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel>
一种选择是将ListBoxItem.IsEnabled设置为false:
<ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
这样可以确保这些项目是不可选择的,但是它们可能无法呈现喜好。要解决此问题,我们可以使用触发器和/或者模板。例如:
<ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle> </ListBox>