1

I have a ListBox that its ItemsSource is given from a class based on the data binded items template. I want to find ListBox.SelectedItem position relative to the ListBox. Since I've used a class to feed ItemsSource, I'm not be able to cast ListBox.SelectedItem (which has a type of object) to the ListBoxItem. (Instead I should cast it to the source class type.)

What's the way? -Thanks


Details: (Arbitrary)

There is a ListBox which implements a Style like so:

<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>

The ListBox has been used as follows:

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

Also there is a class that supports MyListBox data-binding info:

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

    public ImageSource ItemImageSource { get; set; }
}

And to feed the MyListBox:

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

Now, how can I find MyListBox.SelectedItem location relative to the MyListBox?

Mehdi
  • 2,194
  • 2
  • 25
  • 39

1 Answers1

4

Use ItemsControl.ItemContainerGenerator to get a reference to the item container generator for your ListBox (this is the object that creates wrappers for all your databound objects).

Then, use the ItemContainerGenerator.ContainerFromItem method to get a reference to the UIElement that represents the selected ListBoxItem.

Finally, see the answer to this question to for a way of getting the coordinates of the selected item relative to the ListBox.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806