【问题标题】:How to find a data-binded ListBoxItem position?如何找到数据绑定的 ListBoxItem 位置?
【发布时间】:2011-09-20 06:59:35
【问题描述】:

我有一个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数据绑定信息:

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

    public ImageSource ItemImageSource { get; set; }
}

并喂MyListBox

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

现在,我怎样才能找到 MyListBox.SelectedItem 相对于 MyListBox 的位置?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

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

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

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

    【讨论】:

    • 我测试过,没问题!非常感谢;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多