如何查找数据绑定的ListBoxItem位置

本文关键字:数据绑定 ListBoxItem 位置 查找 何查找 | 更新日期: 2023-09-27 18:09:17

我有一个ListBox,它的ItemsSource是基于数据绑定项模板的类给出的。我想找到ListBox.SelectedItem相对于ListBox的位置。由于我使用了一个类来喂养ItemsSource,因此我无法将ListBox.SelectedItem (具有object类型)转换为ListBoxItem(我应该将其强制转换为源类类型)

怎么走?-谢谢


细节:(任意)

有一个ListBox实现了Style:

<Style x:Key="MyListBoxStyle" TargetType="{x:Type ListBox}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border ...>
                    <StackPanel ...>
                        <Image Source="{Binding Path=ItemImageSource}" .../>
                        <TextBlock Text="{Binding Path=ItemTitle}" .../>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

ListBox已被使用如下:

<ListBox x:Name="MyListBox"
         ItemsSource="{Binding}"
         Style="{StaticResource ResourceKey=MyListBoxStyle}"/>

还有一个类支持MyListBox数据绑定info:

internal class MyListBoxItemBinding
{
    public string ItemTitle { get; set; }
    public ImageSource ItemImageSource { get; set; }
}

并输入MyListBox:

MyListBox.ItemsSource = new List<MyListBoxItemBinding> { /* some items */ };

现在,我如何找到MyListBox.SelectedItem相对于MyListBox的位置?

如何查找数据绑定的ListBoxItem位置

使用ItemsControl.ItemContainerGenerator获取对ListBox的项目容器生成器的引用(这是为所有数据绑定对象创建包装器的对象)。

然后,使用ItemContainerGenerator.ContainerFromItem方法获取对代表所选ListBoxItemUIElement的引用。

最后,请参阅此问题的答案,以获取所选项目相对于ListBox的坐标。