【问题标题】:Get index of ListBoxItem - WPF获取 ListBoxItem 的索引 - WPF
【发布时间】:2011-08-08 15:13:00
【问题描述】:

如何获取ListBoxItem 的索引?

ListBox 已通过 XmlDataProvider 绑定到 XML 节点集合。

【问题讨论】:

    标签: c# wpf xaml data-binding listbox


    【解决方案1】:

    我有一个类似的问题,得到了here的回答

    基本上,您将 ListBox 的 AlternationCount 设置为非常高的值,并绑定到每个项目上的 AlternationIndex

    <ListBox AlternationCount="100">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
                                          Path=(ItemsControl.AlternationIndex)}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

    • @Greg:同意,但这是迄今为止我发现使用 ListBox 做到这一点的唯一方法。我希望他们在未来的 WPF 版本中添加一个属性
    • @punker76 我认为 ListBoxes 默认是虚拟化的,所以不应该这样
    • @Rachel 好的,虚拟化是默认设置,但交替索引不起作用。我创建了一个小项目,尝试向下和向上滚动,您将看到 jkarger.de/WpfStackOverflowSpielWiese.exe (.net 4)
    【解决方案2】:

    可以从ItemContainerGenerator获取ListBoxItem的索引:

    listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
    

    【讨论】:

      【解决方案3】:

      属性SelectedIndex 可以工作。这完全取决于您如何进行绑定

      您可能希望将 SelectedIndex 依赖属性绑定到连接到它的数据上下文的对象的某些属性,例如

      <ListBox SelectedIndex="{Binding MySelectedIndex}" ItemsSource="{Binding MyItems}"/>
      

      但你显然可以这样做

      <ListBox SelectedIndex="{Binding MySelectedIndex}">
        <ListBoxItem>1</ListBoxItem>
        <ListBoxItem>2</ListBoxItem>
        <ListBoxItem>3</ListBoxItem>
        <ListBoxItem>4</ListBoxItem>
      </ListBox>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-06
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多