我有一个WPF应用程序,其中包含动态生成的列表框项 . 我想禁用列表框项目的选择或“可聚焦性”,而不禁用每个列表框项中的所有控件(它们包含用户需要能够与之交互的按钮和链接) . 下面是我想要阻止的图片:
此图显示了两个列表框项目 . 我点击了顶部列表框项目的背景区域并选中它,这使文本更难阅读,只是在视觉上没有吸引力 .
您可以将ListBoxItem.IsEnabled属性设置为false,如下所示:
<ListBox x:Name="_sampleListBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
这将使项目无法被选中 . 它可能看起来有点可笑但你可以尝试使用这样的模板:
<ListBox x:Name="_sampleListBox"> <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>
您可以使用此ListBox禁用选择的视觉效果:
<Style x:Key="NoSelectionListBoxItemStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="Background" Value="Transparent"/> <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/> <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/> <Setter Property="Padding" Value="2,0,0,0"/> <Setter Property="FocusVisualStyle"> <Setter.Value> <Style> <!-- This removes focus visualization --> <Setter Property="Control.Template" Value="{x:Null}"/> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> <!-- Some default triggers removed to avoid background changes on selection --> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
也许更清晰的解决方案是使用可能具有其样式的特定项容器创建您自己的ItemsControl .
2 回答
您可以将ListBoxItem.IsEnabled属性设置为false,如下所示:
这将使项目无法被选中 . 它可能看起来有点可笑但你可以尝试使用这样的模板:
您可以使用此ListBox禁用选择的视觉效果:
也许更清晰的解决方案是使用可能具有其样式的特定项容器创建您自己的ItemsControl .