如何查找数据绑定的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
的位置?
使用ItemsControl.ItemContainerGenerator
获取对ListBox
的项目容器生成器的引用(这是为所有数据绑定对象创建包装器的对象)。
然后,使用ItemContainerGenerator.ContainerFromItem
方法获取对代表所选ListBoxItem
的UIElement
的引用。
最后,请参阅此问题的答案,以获取所选项目相对于ListBox
的坐标。