我们有一个场景,我们想要显示一个项目列表,并指出哪个是“当前”项目。项目(带有小箭头标记或更改的背景颜色)。

ItemsControl对我们没有好处,因为我们需要“SelectedItem”的上下文。但是,我们希望以编程方式移动选择,而不允许用户更改它。

是否有一种简单的方法可以使ListBox非交互式?我们可以通过故意吞下鼠标和键盘事件来捏造它,但是我错过了一些基本属性(比如将“IsEnabled”设置为false而不影响其视觉风格)给了我们想要的东西吗?

或者......是否有另一个WPF控件是两个世界中最好的 - 具有SelectedItem属性的ItemsControl?

有帮助吗?

解决方案

一个选项是将 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>

其他提示

我有同样的问题。我通过将IsEnabled设置为true并处理ListBox的PreviewMouseDown事件来解决它。在处理程序集e.Handled为true,如果您不希望它被编辑。

    private void lstSMTs_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        e.Handled = !editRights;
    }

您的ItemsControl / ListBox数据绑定?

我只是想你可以将每个项目的Background Brush从源数据绑定到属性,或者通过转换器传递属性。类似的东西:

  <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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top